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
Let's visualize our regression function with the scatterplot showing the original data set. Herefore, we use the predicted values.
#visualize data points plt.scatter(df1.x, df1.y, color = "y", marker = "o", s = 40) #visualize regression function plt.plot(descriptiveFeatures1, targetFeature1_predict, color = "g") plt.xlabel('x') plt.ylabel('y') plt.title('the data and the regression function') plt.show()
_____no_output_____
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
Now it is your turn. Build a simple linear regression for the data below. Use col1 as descriptive feature and col2 as target feature. Also plot your results.
df2 = pd.DataFrame({'col1': [770, 677, 428, 410, 371, 504, 1136, 695, 551, 550], 'col2': [54, 47, 28, 38, 29, 38, 80, 52, 45, 40]}) #Your turn
_____no_output_____
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
EvaluationUsually, the model and its predictions is not sufficient. In the following we want to evaluate our classifiers. Let's start by computing their error. The sklearn.metrics package contains several errors such as* Mean squared error* Mean absolute error* Mean squared log error* Median absolute error
#computing the squared error of the first model print("Mean squared error model 1: %.2f" % mean_squared_error(targetFeature1, targetFeature1_predict))
Mean squared error model 1: 0.56
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
We can also visualize the errors:
plt.scatter(targetFeature1_predict, (targetFeature1 - targetFeature1_predict) ** 2, color = "blue", s = 10,) ## plotting line to visualize zero error plt.hlines(y = 0, xmin = 0, xmax = 15, linewidth = 2) ## plot title plt.title("Squared errors Model 1") ## function to show plot plt.show()
_____no_output_____
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
Now it is your turn. Compute the mean squared error and visualize the squared errors. Play around using different error metrics.
#Your turn
_____no_output_____
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
Handling multiple descriptive features at once - Multiple linear regressionIn most cases, we will have more than one descriptive feature . As an example we use an example data set of the scikit package. The dataset describes housing prices in Boston based on several attributes. Note, in this format the data is already...
from sklearn import datasets ## imports datasets from scikit-learn df3 = datasets.load_boston() #The sklearn package provides the data splitted into a set of descriptive features and a target feature. #We can easily transform this format into the pandas data frame as used above. descriptiveFeatures3 = pd.DataFrame(df3...
Descriptive features: CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX \ 0 0.00632 18.0 2.31 0.0 0.538 6.575 65.2 4.0900 1.0 296.0 1 0.02731 0.0 7.07 0.0 0.469 6.421 78.9 4.9671 2.0 242.0 2 0.02729 0.0 7.07 0.0 0.469 7.185 61.1 4.9671 2.0 242.0 3 0.0...
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
To predict the housing price we will use a Multiple Linear Regression model. In Python this is very straightforward: we use the same function as for simple linear regression, but our set of descriptive features now contains more than one element (see above).
classifier = LinearRegression() model3 = classifier.fit(descriptiveFeatures3,targetFeature3) targetFeature3_predict = classifier.predict(descriptiveFeatures3) print('Coefficients: \n', classifier.coef_) print('Intercept: \n', classifier.intercept_) print("Mean squared error: %.2f" % mean_squared_error(targetFeature3, ...
Coefficients: [[-1.08011358e-01 4.64204584e-02 2.05586264e-02 2.68673382e+00 -1.77666112e+01 3.80986521e+00 6.92224640e-04 -1.47556685e+00 3.06049479e-01 -1.23345939e-02 -9.52747232e-01 9.31168327e-03 -5.24758378e-01]] Intercept: [36.45948839] Mean squared error: 21.89
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
As you can see above, we have a coefficient for each descriptive feature. Handling categorical descriptive featuresSo far we always encountered numerical dscriptive features, but data sets can also contain categorical attributes. The regression function can only handle numerical input. There are several ways to tranfo...
#example using pandas df4 = pd.DataFrame({'A':['a','b','c'],'B':['c','b','a'] }) one_hot_pd = pd.get_dummies(df4) one_hot_pd #example using scikit from sklearn.preprocessing import LabelEncoder, OneHotEncoder #apply the one hot encoder encoder = OneHotEncoder(categories='auto') encoder.fit(df4) df4_OneHot = encoder.tr...
Transformed by One-hot Encoding: [[1. 0. 0. 0. 0. 1.] [0. 1. 0. 0. 1. 0.] [0. 0. 1. 1. 0. 0.]] Replacing categories by numerical labels: A B 0 0 2 1 1 1 2 2 0
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
Now it is your turn. Perform linear regression using the data set given below. Don't forget to transform your categorical descriptive features. The rental price attribute represents the target variable.
df5 = pd.DataFrame({'Size':[500,550,620,630,665],'Floor':[4,7,9,5,8], 'Energy rating':['C', 'A', 'A', 'B', 'C'], 'Rental price': [320,380,400,390,385] }) #Your turn
_____no_output_____
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
Predicting a categorical target value - Logistic regression We might also encounter data sets where our target feature is categorical. Here we don't transform them into numerical values, but insetad we use a logistic regression function. Luckily, sklearn provides us with a suitable function that is similar to the line...
# Importing the dataset iris = pd.read_csv('iris.csv') print('First look at the data set: ') print(iris.head()) #defining the descriptive and target features descriptiveFeatures_iris = iris[['sepal_length']] #we only use the attribute 'sepal_length' in this example targetFeature_iris = iris['species'] #we want to pre...
First look at the data set: sepal_length sepal_width petal_length petal_width species 0 5.1 3.5 1.4 0.2 setosa 1 4.9 3.0 1.4 0.2 setosa 2 4.7 3.2 1.3 0.2 setosa 3 4.6 3.1 ...
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
Now it is your turn. In the example above we only used the first attribute as descriptive variable. Change the example such that all available attributes are used.
#Your turn
_____no_output_____
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
Note, that the regression classifier (both logistic and non-logistic) can be tweaked using several parameters. This includes, but is not limited to, non-linear regression. Check out the documentation for details and feel free to play around! Support Vector Machines Aside from regression models, the sklearn package als...
from sklearn.svm import SVC #define descriptive and target features as before descriptiveFeatures_iris = iris[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']] targetFeature_iris = iris['species'] #this time, we train an SVM classifier classifier = SVC(C=1, kernel='linear', gamma = 'auto') classifier.fi...
_____no_output_____
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
As explained in the lecture, a support vector machine is defined by its support vectors. In the sklearn package we can access them and their properties very easily:* support_: indicies of support vectors* support_vectors_: the support vectors* n_support_: the number of support vectors for each class
print('Indicies of support vectors:') print(classifier.support_) print('The support vectors:') print(classifier.support_vectors_) print('The number of support vectors for each class:') print(classifier.n_support_)
Indicies of support vectors: [ 23 24 41 52 56 63 66 68 70 72 76 77 83 84 98 106 110 119 123 126 127 129 133 138 146 147 149] The support vectors: [[5.1 3.3 1.7 0.5] [4.8 3.4 1.9 0.2] [4.5 2.3 1.3 0.3] [6.9 3.1 4.9 1.5] [6.3 3.3 4.7 1.6] [6.1 2.9 4.7 1.4] [5.6 3. 4.5 1.5] [6.2 2.2 4.5 1.5] [5.9 3...
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
We can also calculate the distance of the data points to the separating hyperplane by using the decision_function(X) method. Score(X,y) calculates the mean accuracy of the classification. The classification report shows metrics such as precision, recall, f1-score and support. You will learn more about these quality met...
from sklearn.metrics import classification_report classifier.decision_function(descriptiveFeatures_iris) print('Accuracy: \n', classifier.score(descriptiveFeatures_iris,targetFeature_iris)) print('Classification report: \n') print(classification_report(targetFeature_iris, targetFeature_iris_predict))
Accuracy: 0.9933333333333333 Classification report: precision recall f1-score support setosa 1.00 1.00 1.00 50 versicolor 1.00 0.98 0.99 50 virginica 0.98 1.00 0.99 50 accuracy 0.99 ...
Apache-2.0
IDS_2020/RegressionSVM/Instruction4-RegressionSVM-without solutions.ipynb
pmnatos/DataScience
Grade distrubtion by Faculties (used in the appendix)
# note: no NaN's print(df['Fakultet'].unique()) # Number of courses by faculty print(sum(df['Fakultet'] == 'Det Natur- og Biovidenskabelige Fakultet')) print(sum(df['Fakultet'] == 'Det Samfundsvidenskabelige Fakultet')) print(sum(df['Fakultet'] == 'Det Humanistiske Fakultet')) print(sum(df['Fakultet'] == 'Det Sundhedsv...
_____no_output_____
MIT
Exam project/Jacob legemappe/ANALYSIS_JENS_CLEAN.ipynb
tnv875/Group18-NoTeeth
Grade distrubtion by Faculties, weighted against ECTS
# We need to weight the grades according to ECTS points. If we do not small courses will have the same weight as # bigger courses. df['Weigthed_m3'] = df['Credit_edit'] * df[-3] df['Weigthed_00'] = df['Credit_edit'] * df[0] df['Weigthed_02'] = df['Credit_edit'] * df[2] df['Weigthed_4'] = df['Credit_edit'] * df[4] df['...
_____no_output_____
MIT
Exam project/Jacob legemappe/ANALYSIS_JENS_CLEAN.ipynb
tnv875/Group18-NoTeeth
Faculties, weighted against ECTS - droppping -3 and 00
y_no_fail_ects = [] x_no_fail = ['02','4','7','10','12'] # Looking at each faculty for i in tqdm_notebook(df['Fakultet'].unique()): df_faculty = df[df['Fakultet']==i] y_no_fail_ects_inner=[] for k in ['Weigthed_02','Weigthed_4','Weigthed_7','Weigthed_10','Weigthed_12']: y_no_fail_ects_inn...
_____no_output_____
MIT
Exam project/Jacob legemappe/ANALYSIS_JENS_CLEAN.ipynb
tnv875/Group18-NoTeeth
Calculating GPA by faculty
from math import isnan import math #Calculate gpa when ONLY PASSED exams are counted snit = [] for i in range(0,len(df)): x_02 = df[2][i] x_04 = df[4][i] x_07 = df[7][i] x_10 = df[10][i] x_12 = df[12][i] number = (x_12,x_10,x_07,x_04,x_02) grades = [12,10,7,4,2] mydick = dict(zip(gr...
_____no_output_____
MIT
Exam project/Jacob legemappe/ANALYSIS_JENS_CLEAN.ipynb
tnv875/Group18-NoTeeth
Type of assessments broken down by faculties
list_type_ass=list(df['Type of assessmet_edit'].unique()) y_type_ass_inner = [] y_type_ass = [] # Looking at each faculty for i in tqdm_notebook(df['Fakultet'].unique()): df_faculty = df[df['Fakultet']==i] # Running through each type of assessment. for k in list_type_ass: # Summing number of ...
_____no_output_____
MIT
Exam project/Jacob legemappe/ANALYSIS_JENS_CLEAN.ipynb
tnv875/Group18-NoTeeth
Step1. Import and Load Data
!pip install -q pip install git+https://github.com/huggingface/transformers.git !pip install -q datasets from datasets import load_dataset emotions = load_dataset("emotion") import torch device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
_____no_output_____
Apache-2.0
SentimentalAnalysisWithGPTNeo.ipynb
bhadreshpsavani/ExploringSentimentalAnalysis
Step2. Preprocess Data
from transformers import AutoTokenizer model_name = "EleutherAI/gpt-neo-125M" tokenizer = AutoTokenizer.from_pretrained(model_name) def tokenize(batch): return tokenizer(batch["text"], padding=True, truncation=True) tokenizer tokenizer.add_special_tokens({'pad_token': '<|pad|>'}) tokenizer emotions_encoded = emot...
_____no_output_____
Apache-2.0
SentimentalAnalysisWithGPTNeo.ipynb
bhadreshpsavani/ExploringSentimentalAnalysis
parameters
CLUSTER_ALGO = 'KMedoids' C_SHAPE ='circle' #C_SHAPE ='CIRCLE' #C_SHAPE ='ellipse' #N_CLUSTERS = [50,300, 1000] N_CLUSTERS = [3] CLUSTERS_STD = 0.3 N_P_CLUSTERS = [3, 30, 300, 3000] N_CLUSTERS_S = N_CLUSTERS[0] INNER_FOLDS = 3 OUTER_FOLDS = 3
_____no_output_____
MIT
Cluster/kmeans-kmedoids/KMedoids-blobs-3-0.3-varypts.ipynb
bcottman/photon_experiments
includes
%matplotlib inline import matplotlib import matplotlib.pyplot as plt from sklearn.datasets import load_breast_cancer from sklearn.datasets import load_iris from sklearn.datasets import make_blobs from sklearn.datasets import make_moons %load_ext autoreload %autoreload 2 packages = !conda list packages
_____no_output_____
MIT
Cluster/kmeans-kmedoids/KMedoids-blobs-3-0.3-varypts.ipynb
bcottman/photon_experiments
Output registry
from __future__ import print_function import sys, os old__file__ = !pwd __file__ = !cd ../../../photon ;pwd #__file__ = !pwd __file__ = __file__[0] __file__ sys.path.append(__file__) print(sys.path) os.chdir(old__file__[0]) !pwd old__file__[0] import seaborn as sns; sns.set() # for plot styling import numpy as np im...
/opt/conda/lib/python3.7/site-packages/sklearn/externals/joblib/__init__.py:15: DeprecationWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading p...
MIT
Cluster/kmeans-kmedoids/KMedoids-blobs-3-0.3-varypts.ipynb
bcottman/photon_experiments
function defintions
def yield_parameters_ellipse(n_p_clusters): cluster_std = CLUSTERS_STD for n_p_cluster in n_p_clusters: for n_cluster in N_CLUSTERS: print('ncluster:', n_cluster) n_cluster_std = [cluster_std for k in range(n_cluster)] n_samples = [n_p_cluster for k in range(n_cluster...
PhotonCore ARDRegression sklearn.linear_model.ARDRegression Estimator AdaBoostClassifier sklearn.ensemble.AdaBoostClassifier Estimator AdaBoostRegressor sklearn.ensemble.AdaBoostReg...
MIT
Cluster/kmeans-kmedoids/KMedoids-blobs-3-0.3-varypts.ipynb
bcottman/photon_experiments
KMeans blobs
registry.info(CLUSTER_ALGO) def hyper_cluster(cluster_name): if C_SHAPE == 'ellipse' : yield_cluster = yield_parameters_ellipse else: yield_cluster = yield_parameters n_p_clusters = N_P_CLUSTERS for data_X, data_y,n_cluster in yield_cluster(n_p_clusters): simple_output('C...
_____no_output_____
MIT
Cluster/kmeans-kmedoids/KMedoids-blobs-3-0.3-varypts.ipynb
bcottman/photon_experiments
[NTDS'19] assignment 1: network science[ntds'19]: https://github.com/mdeff/ntds_2019[Eda Bayram](https://lts4.epfl.ch/bayram), [EPFL LTS4](https://lts4.epfl.ch) and[Nikolaos Karalias](https://people.epfl.ch/nikolaos.karalias), [EPFL LTS2](https://lts2.epfl.ch). Students* Team: ``* `<Alice Bizeul, Gaia Carparelli, An...
import numpy as np import pandas as pd from matplotlib import pyplot as plt %matplotlib inline
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Question 1: Construct a Citation Graph and a Feature Graph Read the `cora.content` file into a Pandas DataFrame by setting a header for the column names. Check the `README` file.
column_list = ['paper_id'] + [str(i) for i in range(1,1434)] + ['class_label'] pd_content = pd.read_csv('data/cora/cora.content', delimiter='\t', names=column_list) pd_content.head()
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Print out the number of papers contained in each of the reasearch fields.**Hint:** You can use the `value_counts()` function.
pd_content['class_label'].value_counts()
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Select all papers from a field of your choice and store their feature vectors into a NumPy array.Check its shape.
my_field = 'Neural_Networks' features = pd_content[pd_content['class_label'] == my_field].drop(columns=['paper_id','class_label']).to_numpy() features.shape
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Let $D$ be the Euclidean distance matrix whose $(i,j)$ entry corresponds to the Euclidean distance between feature vectors $i$ and $j$.Using the feature vectors of the papers from the field which you have selected, construct $D$ as a Numpy array.
distance = np.zeros([features.shape[0],features.shape[0]]) for i in range(features.shape[0]): distance[i] = np.sqrt(np.sum((features[i,:] - features)**2, axis=1)) distance.shape
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Check the mean pairwise distance $\mathbb{E}[D]$.
# Mean on the upper triangle as the matrix is symetric (we also excluded the diagonal) mean_distance = distance[np.triu_indices(distance.shape[1],1)].mean() print('Mean euclidian distance between feature vectors of papers on Neural Networks: {}'.format(mean_distance))
Mean euclidian distance between feature vectors of papers on Neural Networks: 5.696602496555962
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Plot an histogram of the euclidean distances.
fig,ax = plt.subplots(1,1,figsize=(8, 8)) ax.hist(distance.flatten(), density=True, bins=20, color='salmon', edgecolor='black', linewidth=1); ax.set_title("Histogram of Euclidean distances between Neural-networks papers") ax.set_xlabel("Euclidian Distances") ax.set_ylabel("Frequency") ax.grid(True, which='major', axis=...
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Now create an adjacency matrix for the papers by thresholding the Euclidean distance matrix.The resulting (unweighted) adjacency matrix should have entries$$ A_{ij} = \begin{cases} 1, \; \text{if} \; d(i,j)< \mathbb{E}[D], \; i \neq j, \\ 0, \; \text{otherwise.} \end{cases} $$First, let us choose the mean distance as t...
threshold = mean_distance A_feature = np.where(distance < threshold, 1, 0) np.fill_diagonal(A_feature,0)
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Now read the `cora.cites` file and construct the citation graph by converting the given citation connections into an adjacency matrix.
cora_cites = np.genfromtxt('data/cora/cora.cites', delimiter='\t') papers = np.unique(cora_cites) A_citation = np.zeros([papers.size, papers.size]) for i in range(cora_cites.shape[0]): A_citation[np.where(papers==cora_cites[i,1]),np.where(papers==cora_cites[i,0])] = 1 A_citation.shape
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Get the adjacency matrix of the citation graph for the field that you chose.You have to appropriately reduce the adjacency matrix of the citation graph.
# get the paper id from the chosen field field_id = pd_content[pd_content['class_label'] == my_field]["paper_id"].unique() # get the index of those paper in the A_citation matrix (similar to index on the vector 'papers') field_citation_id = np.empty(field_id.shape[0]).astype(int) for i in range(field_id.shape[0]): ...
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Check if your adjacency matrix is symmetric. Symmetrize your final adjacency matrix if it's not already symmetric.
# a matrix is symetric if it's the same as its transpose print('The citation adjency matrix for papers on Neural Networks is symmetric: {}'.format(np.all(A_citation == A_citation.transpose()))) # symetrize it by taking the maximum between A and A.transposed A_citation = np.maximum(A_citation, A_citation.transpose()) #...
The citation adjency matrix for papers on Neural Networks is symmetric: False After modifiying the matrix, it is symmetric: True
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Check the shape of your adjacency matrix again.
A_citation.shape
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Question 2: Degree Distribution and Moments What is the total number of edges in each graph?
num_edges_feature = int(np.sum(A_feature)/2) # only half of the matrix num_edges_citation = int(np.sum(A_citation)/2) print(f"Number of edges in the feature graph: {num_edges_feature}") print(f"Number of edges in the citation graph: {num_edges_citation}")
Number of edges in the feature graph: 136771 Number of edges in the citation graph: 1175
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Plot the degree distribution histogram for each of the graphs.
degrees_citation = A_citation.sum(axis=1) # degree = nbr of connections --> sum of ones over columns (axis=1) degrees_feature = A_feature.sum(axis=1) deg_hist_normalization = np.ones(degrees_citation.shape[0]) / degrees_citation.shape[0] fig, axes = plt.subplots(1, 2, figsize=(16, 8)) axes[0].set_title('Citation gra...
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Calculate the first and second moments of the degree distribution of each graph.
cit_moment_1 = np.mean(degrees_citation) cit_moment_2 = np.var(degrees_citation) feat_moment_1 = np.mean(degrees_feature) feat_moment_2 = np.var(degrees_feature) print(f"1st moment of citation graph: {cit_moment_1:.3f}") print(f"2nd moment of citation graph: {cit_moment_2:.3f}") print(f"1st moment of feature graph: {...
1st moment of citation graph: 2.873 2nd moment of citation graph: 15.512 1st moment of feature graph: 334.403 2nd moment of feature graph: 55375.549
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
What information do the moments provide you about the graphs?Explain the differences in moments between graphs by comparing their degree distributions. Answer :**The moments provide an idea of the sparsity of the graphs and the way the data is distributed using numerical values. The first moment is associated with the...
smallest_feat_hub_idx = np.argpartition(degrees_feature, degrees_feature.shape[0]-20)[:-20] smallest_feat_hub_idx.sort() reduced_A_feature = A_feature[smallest_feat_hub_idx][:,smallest_feat_hub_idx] smallest_cit_hub_idx = np.argpartition(degrees_citation, degrees_citation.shape[0]-20)[:-20] smallest_cit_hub_idx.sort()...
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Plot the new degree distribution histograms.
reduced_degrees_feat = reduced_A_feature.sum(axis=1) reduced_degrees_cit = reduced_A_citation.sum(axis=1) deg_hist_normalization = np.ones(reduced_degrees_feat.shape[0])/reduced_degrees_feat.shape[0] fig, axes = plt.subplots(1, 2, figsize=(16, 8)) axes[0].set_title('Citation graph degree distribution') axes[0].hist(re...
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Compute the first and second moments for the new graphs.
reduced_cit_moment_1 = np.mean(reduced_degrees_cit) reduced_cit_moment_2 = np.var(reduced_degrees_cit) reduced_feat_moment_1 = np.mean(reduced_degrees_feat) reduced_feat_moment_2 = np.var(reduced_degrees_feat) print(f"Citation graph first moment: {reduced_cit_moment_1:.3f}") print(f"Citation graph second moment: {red...
Citation graph first moment: 1.972 Citation graph second moment: 2.380 Feature graph first moment: 302.308 Feature graph second moment: 50780.035
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Print the number of edges in the reduced graphs.
num_edges_reduced_feature = int(np.sum(reduced_A_feature)/2) num_edges_reduced_citation = int(np.sum(reduced_A_citation)/2) print(f"Number of edges in the reduced feature graph: {num_edges_reduced_feature}") print(f"Number of edges in the reduced citation graph: {num_edges_reduced_citation}")
Number of edges in the reduced feature graph: 120621 Number of edges in the reduced citation graph: 787
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Is the effect of removing the hubs the same for both networks? Look at the percentage changes for each moment. Which of the moments is affected the most and in which graph? Explain why. **Hint:** Examine the degree distributions.
change_cit_moment_1 = (reduced_cit_moment_1-cit_moment_1)/cit_moment_1 change_cit_moment_2 = (reduced_cit_moment_2-cit_moment_2)/cit_moment_2 change_feat_moment_1 = (reduced_feat_moment_1-feat_moment_1)/feat_moment_1 change_feat_moment_2 = (reduced_feat_moment_2-feat_moment_2)/feat_moment_2 print(f"% Percentage of cha...
% Percentage of change for citation 1st moment: -31.343 % Percentage of change for citation 2nd moment: -84.656 % Percentage of change for feature 1st moment: -9.598 % Percentage of change for feature 2nd moment: -8.299
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Answer : **After looking of the percentage of change of moments, we can notice that the removal of the 20 largest hubs affects way more the citation degree distribution than the feature degree distribution. The 2nd moment of the citation degree distribution is reduced by almost 85%, this can be due to the fact that th...
threshold = np.max(distance) diagonal = distance.shape[0] threshold_flag = False epsilon = 0.01*threshold tolerance = 250 while threshold > 0 and not threshold_flag: threshold -= epsilon # steps of 1% of maximum n_edge = int((np.count_nonzero(np.where(distance < threshold, 1, 0)) - diagonal)/2) # wit...
Found a threshold : 2.957 Number of edges in the feature graph: 136771 Number of edges in the feature graph after pruning: 1386 Number of edges in the citation graph: 1175
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Remark:**The distribution of distances (which is a distribution of integers) for this particular field (Neural Networks) doesn't allow a configuration where the number of edges is roughly close (whithin a hundred of edges) to the citation distribution. This is independant of the chosen epsilon . The closest match is 2...
fig, axes = plt.subplots(1, 2, figsize=(12, 6)) axes[0].set_title('Citation graph sparsity') axes[0].spy(A_citation); axes[1].set_title('Feature graph sparsity') axes[1].spy(A_feature_pruned);
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Let $C_{k}(i,j)$ denote the number of paths of length $k$ from node $i$ to node $j$. We define the path matrix $P$, with entries$ P_{ij} = \displaystyle\sum_{k=0}^{N}C_{k}(i,j). $ Calculate the path matrices for both the citation and the unpruned feature graphs for $N =10$. **Hint:** Use [powers of the adjacency matri...
def path_matrix(A, N=10): """Compute the path matrix for matrix A for N power """ power_A = [A] for i in range(N-1): power_A.append(np.matmul(power_A[-1], A)) return np.stack(power_A, axis=2).sum(axis=2) path_matrix_citation = path_matrix(A_citation) path_matrix_feature = path_matrix(A_feature)
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Check the sparsity pattern for both of path matrices.
fig, axes = plt.subplots(1, 2, figsize=(16, 9)) axes[0].set_title('Citation Path matrix sparsity') axes[0].spy(path_matrix_citation); axes[1].set_title('Feature Path matrix sparsity') axes[1].spy(path_matrix_feature, vmin=0, vmax=1); #scaling the color bar
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Now calculate the path matrix of the pruned feature graph for $N=10$. Plot the corresponding sparsity pattern. Is there any difference?
path_matrix_pruned = path_matrix(A_feature_pruned) plt.figure(figsize=(12, 6)) plt.title('Feature Path matrix sparsity') plt.spy(path_matrix_pruned);
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Your answer here: **Many combinations of nodes have a path matrix value of zero now, meaning that they are not within the reach of N = 10 nodes from another node. This makes sense as many edges were removed in the pruning procedure (from 136000 to 1400). Hence, the number of possible paths from i to j was reduced, red...
N=0 diameter = None d_found = False while not d_found: N += 1 P = path_matrix(A_feature, N) if np.count_nonzero(P == 0) == 0: # if there are no zero in P d_found = True diameter = N print(f"The diameter of the feature graph (which is connected) is: {diameter}")
The diameter of the feature graph (which is connected) is: 2
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Check if your guess was correct using [NetworkX](https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.distance_measures.diameter.html).Note: usage of NetworkX is only allowed in this part of Section 1.
import networkx as nx feature_graph = nx.from_numpy_matrix(A_feature) print(f"Diameter of feature graph according to networkx: {nx.diameter(feature_graph)}")
Diameter of feature graph according to networkx: 2
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Section 2: Network Models In this section, you will analyze the feature and citation graphs you constructed in the previous section in terms of the network model types.For this purpose, you can use the NetworkX libary imported below.
import networkx as nx
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Let us create NetworkX graph objects from the adjacency matrices computed in the previous section.
G_citation = nx.from_numpy_matrix(A_citation) print('Number of nodes: {}, Number of edges: {}'. format(G_citation.number_of_nodes(), G_citation.number_of_edges())) print('Number of self-loops: {}, Number of connected components: {}'. format(G_citation.number_of_selfloops(), nx.number_connected_components(G_citation)))
Number of nodes: 818, Number of edges: 1175 Number of self-loops: 0, Number of connected components: 104
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
In the rest of this assignment, we will consider the pruned feature graph as the feature network.
G_feature = nx.from_numpy_matrix(A_feature_pruned) print('Number of nodes: {}, Number of edges: {}'. format(G_feature.number_of_nodes(), G_feature.number_of_edges())) print('Number of self-loops: {}, Number of connected components: {}'. format(G_feature.number_of_selfloops(), nx.number_connected_components(G_feature)))
Number of nodes: 818, Number of edges: 1386 Number of self-loops: 0, Number of connected components: 684
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Question 4: Simulation with Erdős–Rényi and Barabási–Albert models Create an Erdős–Rényi and a Barabási–Albert graph using NetworkX to simulate the citation graph and the feature graph you have. When choosing parameters for the networks, take into account the number of vertices and edges of the original networks. The ...
assert len(G_citation.nodes()) == len(G_feature.nodes()) n = len(G_citation.nodes()) print('The number of nodes ({}) matches the original number of nodes: {}'.format(n,n==A_citation.shape[0]))
The number of nodes (818) matches the original number of nodes: True
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
The number of match shall fit the average of the number of edges in the citation and the feature graph.
m = np.round((G_citation.size() + G_feature.size()) / 2) print('The number of match ({}) fits the average number of edges: {}'.format(m,m==np.round(np.mean([num_edges_citation,num_edges_feature_pruned]))))
The number of match (1280.0) fits the average number of edges: True
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
How do you determine the probability parameter for the Erdős–Rényi graph? Answer:**Based on the principles ruling random networks (no preferential attachment but a random attachment), the expected number of edges is given by : $\langle L \rangle = p\frac{N(N-1)}{2}$ , where $\langle L \rangle$ is the average number o...
p = m*2/(n*(n-1)) G_er = nx.erdos_renyi_graph(n, p)
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Check the number of edges in the Erdős–Rényi graph.
print('My Erdos-Rényi network that simulates the citation graph has {} edges.'.format(G_er.size()))
My Erdos-Rényi network that simulates the citation graph has 1238 edges.
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
How do you determine the preferential attachment parameter for Barabási–Albert graphs? Answer :**The Barabasi-Albert model uses growth and preferential attachement to build a scale-free network. The network is constructed by progressivly adding nodes to the network and adding a fixed number of edges, q, to each node a...
q = int(m/n) G_ba = nx.barabasi_albert_graph(n, q)
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Check the number of edges in the Barabási–Albert graph.
print('My Barabási-Albert network that simulates the citation graph has {} edges.'.format(G_ba.size()))
My Barabási-Albert network that simulates the citation graph has 817 edges.
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Question 5: Giant Component Check the size of the largest connected component in the citation and feature graphs.
giant_citation = max(nx.connected_component_subgraphs(G_citation), key=len) print('The giant component of the citation graph has {} nodes and {} edges.'.format(giant_citation.number_of_nodes(), giant_citation.size())) giant_feature = max(nx.connected_component_subgraphs(G_feature), key=len) print('The giant component o...
The giant component of the feature graph has 117 nodes and 1364 edges.
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Check the size of the giant components in the generated Erdős–Rényi graph.
giant_er = max(nx.connected_component_subgraphs(G_er), key=len) print('The giant component of the Erdos-Rényi network has {} nodes and {} edges.'.format(giant_er.number_of_nodes(), giant_er.size()))
The giant component of the Erdos-Rényi network has 771 nodes and 1234 edges.
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Let us match the number of nodes in the giant component of the feature graph by simulating a new Erdős–Rényi network.How do you choose the probability parameter this time? **Hint:** Recall the expected giant component size from the lectures. Answer :** We can see the average degree of a network/each node as being the ...
GC_node = giant_feature.number_of_nodes() S = GC_node/n avg_k = -1/S*np.log(1-S) p_new = avg_k/(n-1) G_er_new = nx.erdos_renyi_graph(n, p_new)
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Check the size of the new Erdős–Rényi network and its giant component.
print('My new Erdos Renyi network that simulates the citation graph has {} edges.'.format(G_er_new.size())) giant_er_new = max(nx.connected_component_subgraphs(G_er_new), key=len) print('The giant component of the new Erdos-Rényi network has {} nodes and {} edges.'.format(giant_er_new.number_of_nodes(), giant_er_new.si...
My new Erdos Renyi network that simulates the citation graph has 437 edges. The giant component of the new Erdos-Rényi network has 208 nodes and 210 edges.
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Question 6: Degree Distributions Recall the degree distribution of the citation and the feature graph.
fig, axes = plt.subplots(1, 2, figsize=(15, 6),sharex = True) axes[0].set_title('Citation graph') citation_degrees = [deg for (node, deg) in G_citation.degree()] axes[0].hist(citation_degrees, bins=20, color='salmon', edgecolor='black', linewidth=1); axes[1].set_title('Feature graph') feature_degrees = [deg for (node,...
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
What does the degree distribution tell us about a network? Can you make a prediction on the network model type of the citation and the feature graph by looking at their degree distributions? Answer : **The degree distribution tell us about the sparsity of a network.Both show a power law degree distribution (many nodes...
fig, axes = plt.subplots(1, 3, figsize=(20, 8)) axes[0].set_title('Erdos-Rényi network') er_degrees = [deg for (node, deg) in G_er.degree()] axes[0].hist(er_degrees, bins=10, color='salmon', edgecolor='black', linewidth=1) axes[1].set_title('Barabási-Albert network') ba_degrees = [deg for (node, deg) in G_ba.degree()...
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
In terms of the degree distribution, is there a good match between the citation and feature graphs and the simulated networks?For the citation graph, choose one of the simulated networks above that match its degree distribution best. Indicate your preference below. Answer : **Regarding the feature network, none of the...
G_config = nx.configuration_model(feature_degrees) print('Configuration model has {} nodes and {} edges.'.format(G_config.number_of_nodes(), G_config.size()))
Configuration model has 818 nodes and 1386 edges.
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Does it mean that we create the same graph with the feature graph by the configuration model? If not, how do you understand that they are not the same? Answer : **No we don't create the same graph, the number of edges, nodes and degree distribution can be the same but the links can be different. For example, in a grou...
nx.average_clustering(G_citation) nx.average_clustering(G_feature)
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
What does the clustering coefficient tell us about a network? Comment on the values you obtain for the citation and feature graph. Answer :**Clustering coefficient is linked to the presence of subgroups (or clusters) in the network. A high clustering coefficient means that a node is very likely to be part of a subgrou...
nx.average_clustering(G_er) nx.average_clustering(G_ba) nx.average_clustering(nx.Graph(G_config))
_____no_output_____
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Comment on the values you obtain for the simulated networks. Is there any good match to the citation or feature graph in terms of clustering coefficient? Answer : **No, there is not any match. The clustering coefficients are rather small compared to the ones for feature and citation graphs. Random networks have genera...
k = m*2/n p = (nx.average_clustering(G_citation) + nx.average_clustering(G_feature))*0.8 G_pwc = nx.powerlaw_cluster_graph(n, int(k), p) print('Power law cluster model has {} edges.'.format(G_pwc.size())) print('Power law cluster model has a clustering coefficient of {}'.format(nx.average_clustering(G_pwc))) print('C...
Power law cluster model has 2440 edges. Power law cluster model has a clustering coefficient of 0.16384898371644135 Citation model has 1175 edges. Citation model has a clustering coefficient of 0.21693567980632222 Feature model has 1386 edges. Feature model has a clustering coefficient of 0.1220744470334593
Apache-2.0
Assignments/1_network_science.ipynb
carparel/NTDS
Implementing a CGAN for the Iris data set to generate synthetic data Import necessary modules and packages
import os while os.path.basename(os.getcwd()) != 'Synthetic_Data_GAN_Capstone': os.chdir('..') from utils.utils import * safe_mkdir('experiments') from utils.data_loading import load_raw_dataset import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.op...
_____no_output_____
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Set random seed for reproducibility
manualSeed = 999 print("Random Seed: ", manualSeed) random.seed(manualSeed) torch.manual_seed(manualSeed)
Random Seed: 999
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Import and briefly inspect data
iris = load_raw_dataset('iris') iris.head()
_____no_output_____
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Preprocessing dataSplit 50-50 so we can demonstrate the effectiveness of additional data
x_train, x_test, y_train, y_test = train_test_split(iris.drop(columns='species'), iris.species, test_size=0.5, stratify=iris.species, random_state=manualSeed) print("x_train:", x_train.shape) print("x_test:", x_test.shape)
x_train: (75, 4) x_test: (75, 4)
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Model parameters (feel free to play with these)
nz = 32 # Size of generator noise input H = 16 # Size of hidden network layer out_dim = x_train.shape[1] # Size of output bs = x_train.shape[0] # Full data set nc = 3 # 3 different types of label in this problem num_batches = 1 num_epochs = 10000 exp_name = 'experiments/iris_1x16' safe_mkdir(exp_name)
_____no_output_____
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Adam optimizer hyperparametersI set these based on the original paper, but feel free to play with them as well.
lr = 2e-4 beta1 = 0.5 beta2 = 0.999
_____no_output_____
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Set the device
device = torch.device("cuda:0" if (torch.cuda.is_available()) else "cpu")
_____no_output_____
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Scale continuous inputs for neural networks
scaler = StandardScaler() x_train = scaler.fit_transform(x_train) x_train_tensor = torch.tensor(x_train, dtype=torch.float) y_train_dummies = pd.get_dummies(y_train) y_train_dummies_tensor = torch.tensor(y_train_dummies.values, dtype=torch.float)
_____no_output_____
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Instantiate nets
netG = CGAN_Generator(nz=nz, H=H, out_dim=out_dim, nc=nc, bs=bs, lr=lr, beta1=beta1, beta2=beta2).to(device) netD = CGAN_Discriminator(H=H, out_dim=out_dim, nc=nc, lr=lr, beta1=beta1, beta2=beta2).to(device)
_____no_output_____
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Print modelsI chose to avoid using sequential mode in case I wanted to create non-sequential networks, it is more flexible in my opinion, but does not print out as nicely
print(netG) print(netD)
CGAN_Generator( (fc1): Linear(in_features=35, out_features=16, bias=True) (output): Linear(in_features=16, out_features=4, bias=True) (act): LeakyReLU(negative_slope=0.2) (loss_fn): BCELoss() ) CGAN_Discriminator( (fc1): Linear(in_features=7, out_features=16, bias=True) (output): Linear(in_features=16, out_...
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Define labels
real_label = 1 fake_label = 0
_____no_output_____
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Training LoopLook through the comments to better understand the steps that are taking place
print("Starting Training Loop...") for epoch in range(num_epochs): for i in range(num_batches): # Only one batch per epoch since our data is horrifically small # Update Discriminator # All real batch first real_data = x_train_tensor.to(device) # Format batch (entire data set in this case) ...
Starting Training Loop... [1/10000] Loss_D: 1.3938 Loss_G: 0.7742 D(x): 0.4603 D(G(z)): 0.4609 / 0.4611 [1001/10000] Loss_D: 1.3487 Loss_G: 0.7206 D(x): 0.5089 D(G(z)): 0.4883 / 0.4882 [2001/10000] Loss_D: 1.3557 Loss_G: 0.7212 D(x): 0.5025 D(G(z)): 0.4864 / 0.4864 [3001/10000] Loss_D: 1.4118 Loss_G: 0.6679 D(x): 0.502...
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Output diagnostic plots tracking training progress and statistics
%matplotlib inline training_plots(netD=netD, netG=netG, num_epochs=num_epochs, save=exp_name) plot_layer_scatters(netG, title="Generator", save=exp_name) plot_layer_scatters(netD, title="Discriminator", save=exp_name)
/home/aj/.local/lib/python3.7/site-packages/matplotlib/figure.py:445: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure. % get_backend())
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
It looks like training stabilized fairly quickly, after only a few thousand iterations. The fact that the weight norm increased over time probably means that this network would benefit from some regularization. Compare performance of training on fake data versus real dataIn this next section, we will lightly tune two ...
y_test_dummies = pd.get_dummies(y_test) print("Dummy columns match?", all(y_train_dummies.columns == y_test_dummies.columns)) x_test = scaler.transform(x_test) labels_list = [x for x in y_train_dummies.columns] param_grid = {'tol': [1e-9, 1e-8, 1e-7, 1e-6, 1e-5], 'C': [0.5, 0.75, 1, 1.25], '...
Dummy columns match? True
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Train on real data
model_real, score_real = train_test_logistic_reg(x_train, y_train, x_test, y_test, param_grid=param_grid, cv=5, random_state=manualSeed, labels=labels_list)
Accuracy: 0.92 Best Parameters: {'C': 1.25, 'l1_ratio': 0.5, 'tol': 1e-09} precision recall f1-score support Iris-setosa 1.00 1.00 1.00 25 Iris-versicolor 0.85 0.92 0.88 25 Iris-virginica 0.91 0.84 0.87 25 accuracy...
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Train on various levels of fake data
test_range = [75, 150, 300, 600, 1200] fake_bs = bs fake_models = [] fake_scores = [] for size in test_range: num_batches = size // fake_bs + 1 genned_data = np.empty((0, out_dim)) genned_labels = np.empty(0) rem = size while rem > 0: curr_size = min(fake_bs, rem) noise = torch.randn...
For size of: 75 Accuracy: 0.92 Best Parameters: {'C': 0.5, 'l1_ratio': 0.25, 'tol': 1e-09} precision recall f1-score support Iris-setosa 1.00 1.00 1.00 25 Iris-versicolor 0.88 0.88 0.88 25 Iris-virginica 0.88 0.88 0.88 25 ...
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Well, it looks like this experiment was a success. The models trained on fake data were actually able to outperform models trained on real data, which supports the belief that the CGAN is able to understand the distribution of the data it was trained on and generate meaningful examples that can be used to add additiona...
iris_plot_scatters(genned_data, genned_labels, "Fake Data", scaler, alpha=0.5, save=exp_name) # Fake data iris_plot_scatters(iris.drop(columns='species'), np.array(iris.species), "Full Real Data Set", alpha=0.5, save=exp_name) # All real data iris_plot_densities(genned_data, genned_labels, "Fake Data", scaler, save=e...
_____no_output_____
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Finally, I present a summary of the test results ran above
fake_data_training_plots(real_range=bs, score_real=score_real, test_range=test_range, fake_scores=fake_scores, save=exp_name)
/home/aj/.local/lib/python3.7/site-packages/matplotlib/figure.py:445: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure. % get_backend())
MIT
notebooks/reports/iris.ipynb
Atrus619/CSDGAN
Predictive Maintenance using Machine Learning on Sagemaker*Part 3 - Timeseries data preparation* Initialization---Directory structure to run this notebook:```nasa-turbofan-rul-lstm|+--- data| || +--- interim: intermediate data we can manipulate and process| || \--- raw: *immutable* data downloaded from the so...
%load_ext autoreload import matplotlib.pyplot as plt import sagemaker import boto3 import os import errno import pandas as pd import numpy as np import seaborn as sns import json import sys import s3fs import mxnet as mx import joblib %matplotlib inline %autoreload 2 sns.set_style('darkgrid') sys.path.append('../src'...
_____no_output_____
MIT-0
nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb
michaelhoarau/sagemaker-predictive-maintenance
Loading data from the previous notebook
# Load data from the notebook local storage: %store -r reduced_train_data %store -r reduced_test_data # If the data are not present in the notebook local storage, we need to load them from disk: success_msg = 'Loaded "reduced_train_data"' if 'reduced_train_data' not in locals(): print('Nothing in notebook store, t...
(13096, 26)
MIT-0
nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb
michaelhoarau/sagemaker-predictive-maintenance
Study parameters
sequence_length = 20
_____no_output_____
MIT-0
nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb
michaelhoarau/sagemaker-predictive-maintenance
Normalization--- Normalizing the training dataFirst, we build some scalers based on the training data:
from sklearn import preprocessing # Isolate the columns to normalize: normalized_cols = reduced_train_data.columns.difference(['true_rul', 'piecewise_rul']) # Build MinMax scalers for the features and the labels: features_scaler = preprocessing.MinMaxScaler() labels_scaler = preprocessing.MinMaxScaler() # Normalize ...
(20631, 19)
MIT-0
nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb
michaelhoarau/sagemaker-predictive-maintenance
Normalizing the testing dataNext, we apply these normalizers to the testing data:
normalized_test_data = pd.DataFrame( features_scaler.transform(reduced_test_data[normalized_cols]), columns=normalized_cols, index=reduced_test_data.index ) reduced_test_data['piecewise_rul'] = reduced_test_data['piecewise_rul'].astype(np.float64) normalized_test_labels = pd.DataFrame( labels_scaler.t...
(13096, 26)
MIT-0
nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb
michaelhoarau/sagemaker-predictive-maintenance
Sequences generation---
from lstm_utils import generate_sequences, generate_labels, generate_training_sequences, generate_testing_sequences # Building features, target and engine unit lists: features = normalized_train_data.columns.difference(['true_rul', 'piecewise_rul']) target = ['piecewise_rul'] unit_list = list(set(normalized_train_data...
Unit 1 test sequence ignored, not enough data points. Unit 22 test sequence ignored, not enough data points. Unit 39 test sequence ignored, not enough data points. Unit 85 test sequence ignored, not enough data points. train_sequences: (18631, 20, 17) train_labels: (18631, 1) test_sequences: (11035, 20, 17) test_labels...
MIT-0
nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb
michaelhoarau/sagemaker-predictive-maintenance
Visualizing the sequencesLet's visualize the sequences we built for an engine (e.g. unit 3 in the example below) to understand what will be fed to the LSTM model:
from lstm_utils import plot_timestep, plot_text # We use the normalized sequences for the plot but the original data for the label (RUL) for understanding purpose: current_unit = 1 tmp_sequences = generate_training_sequences(normalized_train_data, sequence_length, features, [current_unit]) tmp_labels = generate_traini...
Sequences generated for unit 1:
MIT-0
nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb
michaelhoarau/sagemaker-predictive-maintenance
Cleanup--- Storing data for the next notebook
%store labels_scaler %store test_sequences %store test_labels %store unit_span #columns = normalized_train_data.columns.tolist() #%store columns #%store train_sequences #%store train_labels #%store normalized_train_data #%store normalized_test_data #%store sequence_length
Stored 'labels_scaler' (MinMaxScaler) Stored 'test_sequences' (ndarray) Stored 'test_labels' (ndarray) Stored 'unit_span' (list)
MIT-0
nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb
michaelhoarau/sagemaker-predictive-maintenance
Persisting these data to diskThis is useful in case you want to be able to execute each notebook independantly (from one session to another) and don't want to reexecute every notebooks whenever you want to focus on a particular step. Let's start by persisting train and test sequences and the associated labels:
import h5py as h5 train_data = os.path.join(PROCESSED_DATA, 'train.h5') with h5.File(train_data, 'w') as ftrain: ftrain.create_dataset('train_sequences', data=train_sequences) ftrain.create_dataset('train_labels', data=train_labels) ftrain.close() test_data = os.path.join(PROCESSED_DATA, 'test.h5') with h...
_____no_output_____
MIT-0
nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb
michaelhoarau/sagemaker-predictive-maintenance
Pushing these files to S3:
sagemaker_session = sagemaker.Session() bucket = sagemaker_session.default_bucket() prefix = 'nasa-rul-lstm/data' train_data_location = 's3://{}/{}'.format(bucket, prefix) s3_resource = boto3.Session().resource('s3') s3_resource.Bucket(bucket).Object('{}/train/train.h5'.format(prefix)).upload_file(train_data) s3_resou...
Stored 'data_channels' (dict)
MIT-0
nasa-turbofan-rul-lstm/notebooks/3 - Data preparation.ipynb
michaelhoarau/sagemaker-predictive-maintenance