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
数学和统计方法数组的数学函数对数组或数组某个轴向的数据进行统计计算;既可以通过数据实例方法调用;也可以当做nump顶级函数使用.
arr = np.arange(10).reshape(2,5) print arr print arr.mean()#计算数组平均值 print arr.mean(axis = 0)#可指定轴,用以统计该轴上的值 print arr.mean(axis = 1) print np.mean(arr) print np.mean(arr,axis = 0) print np.mean(arr,axis = 1) print arr.sum()#计算数组和 print arr.sum(axis = 0) print arr.sum(axis = 1) print np.sum(arr) print np.sum(arr,axis = ...
[[ 1 2 3 4 5] [ 6 7 8 9 10]] [ 1 2 6 24 120 720 5040 40320 362880 3628800]
Apache-2.0
numpy/2-numpy-middle.ipynb
GmZhang3/data-science-ipython-notebooks
用于布尔型数组的方法any()测试布尔型数组是否存在一个或多个Trueall()检查数组中所有值是否都为True
arr = np.random.randn(10) # print bools = arr > 0 print bools print bools.any() print np.any(bools) print bools.all() print np.all(bools) arr = np.array([0,1,2,3,4]) print arr.any()#非布尔型数组,所有非0元素会被当做True
[ True False True True True False True True True False] True True False False True
Apache-2.0
numpy/2-numpy-middle.ipynb
GmZhang3/data-science-ipython-notebooks
排序
arr = np.random.randn(10) print arr arr.sort()#与python内置列表排序一样;就地排序,会修改数组本身 print arr arr = np.random.randn(10) print arr print np.sort(arr)#返回数组已排序副本
[ 1.00826129 -1.33200021 -2.09423152 1.14618429 -1.94373366 -1.19964262 -0.97484352 -0.25508501 0.95594379 -0.92684744] [-2.09423152 -1.94373366 -1.33200021 -1.19964262 -0.97484352 -0.92684744 -0.25508501 0.95594379 1.00826129 1.14618429] [-0.13764091 -0.44657322 -0.4725095 -2.25229905 0.92481373 -0.4272677 -...
Apache-2.0
numpy/2-numpy-middle.ipynb
GmZhang3/data-science-ipython-notebooks
唯一化及其他的集合逻辑numpy针对一维数组的基本集合运算np.unique()找出数组中的唯一值,并返回已排序的结果
names = np.array(['bob', 'joe', 'will', 'bob', 'will', 'joe', 'joe']) print names print np.unique(names)
['bob' 'joe' 'will' 'bob' 'will' 'joe' 'joe'] ['bob' 'joe' 'will']
Apache-2.0
numpy/2-numpy-middle.ipynb
GmZhang3/data-science-ipython-notebooks
线性代数
#矩阵乘法 x = np.array([[1,2,3],[4,5,6]]) y = np.array([[6,23],[-1,7],[8,9]]) print x print y print x.dot(y) print np.dot(x,y)
[[1 2 3] [4 5 6]] [[ 6 23] [-1 7] [ 8 9]] [[ 28 64] [ 67 181]] [[ 28 64] [ 67 181]]
Apache-2.0
numpy/2-numpy-middle.ipynb
GmZhang3/data-science-ipython-notebooks
随机数生成numpy.random模块对python内置的random进行补充,增接了一些用于高效生成多生概率分布的样本值的函数
#从给定的上下限范围内随机选取整数 print np.random.randint(10) #产生正态分布的样本值 print np.random.randn(3,2)
[[-0.05199971 -1.95031704] [-1.42560357 0.78544126] [ 0.47068984 -0.51157053]]
Apache-2.0
numpy/2-numpy-middle.ipynb
GmZhang3/data-science-ipython-notebooks
数组组合
a = np.array([1,2,3]) b = np.array([4,5,6]) c = np.arange(6).reshape(2,3) d = np.arange(2,8).reshape(2,3) print(a) print(b) print(c) print(d) np.concatenate([c,d]) # In machine learning, useful to enrich or # add new/concatenate features with hstack np.hstack([c, d]) # Use broadcasting when needed to do this automatic...
_____no_output_____
Apache-2.0
numpy/2-numpy-middle.ipynb
GmZhang3/data-science-ipython-notebooks
A Scientific Deep Dive Into SageMaker LDA1. [Introduction](Introduction)1. [Setup](Setup)1. [Data Exploration](DataExploration)1. [Training](Training)1. [Inference](Inference)1. [Epilogue](Epilogue) Introduction***Amazon SageMaker LDA is an unsupervised learning algorithm that attempts to describe a set of observatio...
!conda install -y scipy %matplotlib inline import os, re, tarfile import boto3 import matplotlib.pyplot as plt import mxnet as mx import numpy as np np.set_printoptions(precision=3, suppress=True) # some helpful utility functions are defined in the Python module # "generate_example_data" located in the same director...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Setup****This notebook was created and tested on an ml.m4.xlarge notebook instance.*We first need to specify some AWS credentials; specifically data locations and access roles. This is the only cell of this notebook that you will need to edit. In particular, we need the following data:* `bucket` - An S3 bucket accessi...
from sagemaker import get_execution_role role = get_execution_role() bucket = '<your_s3_bucket_name_here>' prefix = 'sagemaker/lda_science' print('Training input/output will be stored in {}/{}'.format(bucket, prefix)) print('\nIAM Role: {}'.format(role))
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
The LDA ModelAs mentioned above, LDA is a model for discovering latent topics describing a collection of documents. In this section we will give a brief introduction to the model. Let,* $M$ = the number of *documents* in a corpus* $N$ = the average *length* of a document.* $V$ = the size of the *vocabulary* (the total...
print('Generating example data...') num_documents = 6000 known_alpha, known_beta, documents, topic_mixtures = generate_griffiths_data( num_documents=num_documents, num_topics=10) num_topics, vocabulary_size = known_beta.shape # separate the generated data into training and tests subsets num_documents_training = i...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Let's start by taking a closer look at the documents. Note that the vocabulary size of these data is $V = 25$. The average length of each document in this data set is 150. (See `generate_griffiths_data.py`.)
print('First training document =\n{}'.format(documents_training[0])) print('\nVocabulary size = {}'.format(vocabulary_size)) print('Length of first document = {}'.format(documents_training[0].sum())) average_document_length = documents.sum(axis=1).mean() print('Observed average document length = {}'.format(average_docu...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
The example data set above also returns the LDA parameters,$$(\alpha, \beta)$$used to generate the documents. Let's examine the first topic and verify that it is a probability distribution on the vocabulary.
print('First topic =\n{}'.format(known_beta[0])) print('\nTopic-word probability matrix (beta) shape: (num_topics, vocabulary_size) = {}'.format(known_beta.shape)) print('\nSum of elements of first topic = {}'.format(known_beta[0].sum()))
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Unlike some clustering algorithms, one of the versatilities of the LDA model is that a given word can belong to multiple topics. The probability of that word occurring in each topic may differ, as well. This is reflective of real-world data where, for example, the word *"rover"* appears in a *"dogs"* topic as well as i...
print('Topic #1:\n{}'.format(known_beta[0])) print('Topic #6:\n{}'.format(known_beta[5]))
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Human beings are visual creatures, so it might be helpful to come up with a visual representation of these documents.In the below plots, each pixel of a document represents a word. The greyscale intensity is a measure of how frequently that word occurs within the document. Below we plot the first few documents of the t...
%matplotlib inline fig = plot_lda(documents_training, nrows=3, ncols=4, cmap='gray_r', with_colorbar=True) fig.suptitle('$w$ - Document Word Counts') fig.set_dpi(160)
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
When taking a close look at these documents we can see some patterns in the word distributions suggesting that, perhaps, each topic represents a "column" or "row" of words with non-zero probability and that each document is composed primarily of a handful of topics.Below we plots the *known* topic-word probability dist...
%matplotlib inline fig = plot_lda(known_beta, nrows=1, ncols=10) fig.suptitle(r'Known $\beta$ - Topic-Word Probability Distributions') fig.set_dpi(160) fig.set_figheight(2)
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
These 10 topics were used to generate the document corpus. Next, we will learn about how this is done. Generating DocumentsLDA is a generative model, meaning that the LDA parameters $(\alpha, \beta)$ are used to construct documents word-by-word by drawing from the topic-word distributions. In fact, looking closely at ...
print('First training document =\n{}'.format(documents_training[0])) print('\nVocabulary size = {}'.format(vocabulary_size)) print('Length of first document = {}'.format(documents_training[0].sum())) print('First training document topic mixture =\n{}'.format(topic_mixtures_training[0])) print('\nNumber of topics = {}'....
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
We plot the first document along with its topic mixture. We also plot the topic-word probability distributions again for reference.
%matplotlib inline fig, (ax1,ax2) = plt.subplots(2, 1) ax1.matshow(documents[0].reshape(5,5), cmap='gray_r') ax1.set_title(r'$w$ - Document', fontsize=20) ax1.set_xticks([]) ax1.set_yticks([]) cax2 = ax2.matshow(topic_mixtures[0].reshape(1,-1), cmap='Reds', vmin=0, vmax=1) cbar = fig.colorbar(cax2, orientation='hori...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Finally, let's plot several documents with their corresponding topic mixtures. We can see how topics with large weight in the document lead to more words in the document within the corresponding "row" or "column".
%matplotlib inline fig = plot_lda_topics(documents_training, 3, 4, topic_mixtures=topic_mixtures) fig.suptitle(r'$(w,\theta)$ - Documents with Known Topic Mixtures') fig.set_dpi(160)
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Training***In this section we will give some insight into how AWS SageMaker LDA fits an LDA model to a corpus, create an run a SageMaker LDA training job, and examine the output trained model. Topic Estimation using Tensor DecompositionsGiven a document corpus, Amazon SageMaker LDA uses a spectral tensor decompositio...
# convert documents_training to Protobuf RecordIO format recordio_protobuf_serializer = numpy_to_record_serializer() fbuffer = recordio_protobuf_serializer(documents_training) # upload to S3 in bucket/prefix/train fname = 'lda.data' s3_object = os.path.join(prefix, 'train', fname) boto3.Session().resource('s3').Bucket...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Next, we specify a Docker container containing the SageMaker LDA algorithm. For your convenience, a region-specific container is automatically chosen for you to minimize cross-region data communication
containers = { 'us-west-2': '266724342769.dkr.ecr.us-west-2.amazonaws.com/lda:latest', 'us-east-1': '766337827248.dkr.ecr.us-east-1.amazonaws.com/lda:latest', 'us-east-2': '999911452149.dkr.ecr.us-east-2.amazonaws.com/lda:latest', 'eu-west-1': '999678624901.dkr.ecr.eu-west-1.amazonaws.com/lda:latest' } ...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Training ParametersParticular to a SageMaker LDA training job are the following hyperparameters:* **`num_topics`** - The number of topics or categories in the LDA model. * Usually, this is not known a priori. * In this example, howevever, we know that the data is generated by five topics.* **`feature_dim`** - The si...
session = sagemaker.Session() # specify general training job information lda = sagemaker.estimator.Estimator( container, role, output_path='s3://{}/{}/output'.format(bucket, prefix), train_instance_count=1, train_instance_type='ml.c4.2xlarge', sagemaker_session=session, ) # set algorithm-speci...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
If you see the message> `===== Job Complete =====`at the bottom of the output logs then that means training sucessfully completed and the output LDA model was stored in the specified output path. You can also view information about and the status of a training job using the AWS SageMaker console. Just click on the "Job...
print('Training job name: {}'.format(lda.latest_training_job.job_name))
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Inspecting the Trained ModelWe know the LDA parameters $(\alpha, \beta)$ used to generate the example data. How does the learned model compare the known one? In this section we will download the model data and measure how well SageMaker LDA did in learning the model.First, we download the model data. SageMaker will ou...
# download and extract the model file from S3 job_name = lda.latest_training_job.job_name model_fname = 'model.tar.gz' model_object = os.path.join(prefix, 'output', job_name, 'output', model_fname) boto3.Session().resource('s3').Bucket(bucket).Object(model_object).download_file(fname) with tarfile.open(fname) as tar: ...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Presumably, SageMaker LDA has found the topics most likely used to generate the training corpus. However, even if this is case the topics would not be returned in any particular order. Therefore, we match the found topics to the known topics closest in L1-norm in order to find the topic permutation.Note that we will us...
permutation, learned_beta = match_estimated_topics(known_beta, learned_beta_permuted) learned_alpha = learned_alpha_permuted[permutation] fig = plot_lda(np.vstack([known_beta, learned_beta]), 2, 10) fig.set_dpi(160) fig.suptitle('Known vs. Found Topic-Word Probability Distributions') fig.set_figheight(3) beta_error =...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Not bad!In the eyeball-norm the topics match quite well. In fact, the topic-word distribution error is approximately 2%. Inference***A trained model does nothing on its own. We now want to use the model we computed to perform inference on data. For this example, that means predicting the topic mixture representing a g...
lda_inference = lda.deploy( initial_instance_count=1, instance_type='ml.m4.xlarge', # LDA inference may work better at scale on ml.c4 instances )
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Congratulations! You now have a functioning SageMaker LDA inference endpoint. You can confirm the endpoint configuration and status by navigating to the "Endpoints" tab in the AWS SageMaker console and selecting the endpoint matching the endpoint name, below:
print('Endpoint name: {}'.format(lda_inference.endpoint))
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
With this realtime endpoint at our fingertips we can finally perform inference on our training and test data.We can pass a variety of data formats to our inference endpoint. In this example we will demonstrate passing CSV-formatted data. Other available formats are JSON-formatted, JSON-sparse-formatter, and RecordIO Pr...
lda_inference.content_type = 'text/csv' lda_inference.serializer = csv_serializer lda_inference.deserializer = json_deserializer
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
We pass some test documents to the inference endpoint. Note that the serializer and deserializer will atuomatically take care of the datatype conversion.
results = lda_inference.predict(documents_test[:12]) print(results)
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
It may be hard to see but the output format of SageMaker LDA inference endpoint is a Python dictionary with the following format.```{ 'predictions': [ {'topic_mixture': [ ... ] }, {'topic_mixture': [ ... ] }, {'topic_mixture': [ ... ] }, ... ]}```We extract the topic mixtures, themselves, corresponding to...
inferred_topic_mixtures_permuted = np.array([prediction['topic_mixture'] for prediction in results['predictions']]) print('Inferred topic mixtures (permuted):\n\n{}'.format(inferred_topic_mixtures_permuted))
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Inference AnalysisRecall that although SageMaker LDA successfully learned the underlying topics which generated the sample data the topics were in a different order. Before we compare to known topic mixtures $\theta \in \mathbb{R}^K$ we should also permute the inferred topic mixtures
inferred_topic_mixtures = inferred_topic_mixtures_permuted[:,permutation] print('Inferred topic mixtures:\n\n{}'.format(inferred_topic_mixtures))
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Let's plot these topic mixture probability distributions alongside the known ones.
%matplotlib inline # create array of bar plots width = 0.4 x = np.arange(10) nrows, ncols = 3, 4 fig, ax = plt.subplots(nrows, ncols, sharey=True) for i in range(nrows): for j in range(ncols): index = i*ncols + j ax[i,j].bar(x, topic_mixtures_test[index], width, color='C0') ax[i,j].bar(x+w...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
In the eyeball-norm these look quite comparable.Let's be more scientific about this. Below we compute and plot the distribution of L1-errors from **all** of the test documents. Note that we send a new payload of test documents to the inference endpoint and apply the appropriate permutation to the output.
%%time # create a payload containing all of the test documents and run inference again # # TRY THIS: # try switching between the test data set and a subset of the training # data set. It is likely that LDA inference will perform better against # the training set than the holdout test set. # payload_documents = d...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Machine learning algorithms are not perfect and the data above suggests this is true of SageMaker LDA. With more documents and some hyperparameter tuning we can obtain more accurate results against the known topic-mixtures.For now, let's just investigate the documents-topic mixture pairs that seem to do well as well as...
N = 6 good_idx = (l1_errors < 0.05) good_documents = payload_documents[good_idx][:N] good_topic_mixtures = inferred_topic_mixtures[good_idx][:N] poor_idx = (l1_errors > 0.3) poor_documents = payload_documents[poor_idx][:N] poor_topic_mixtures = inferred_topic_mixtures[poor_idx][:N] %matplotlib inline fig = plot_lda_...
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
In this example set the documents on which inference was not as accurate tend to have a denser topic-mixture. This makes sense when extrapolated to real-world datasets: it can be difficult to nail down which topics are represented in a document when the document uses words from a large subset of the vocabulary. Stop /...
sagemaker.Session().delete_endpoint(lda_inference.endpoint)
_____no_output_____
Apache-2.0
scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb
karim7262/amazon-sagemaker-examples
Load Library
!pip install wget !pip install keras-tcn import wget import matplotlib.pyplot as plt import numpy as np import pandas as pd from tensorflow.keras import Input, Model from tensorflow.keras.layers import Dense from tqdm.notebook import tqdm from tcn import TCN wget.download("https://github.com/philipperemy/keras-tcn/raw...
_____no_output_____
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
Read the dataset
milk = pd.read_csv('monthly-milk-production-pounds-p.csv', index_col=0, parse_dates=True)
_____no_output_____
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
Display top5 Record
print(milk.shape) milk.head()
(168, 1)
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
Lookback 12 month windows
lookback_window = 12
_____no_output_____
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
Convert Milk Data into Numpy Array
milk = milk.values
_____no_output_____
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
Convert in to X, y format
x = [] y = [] for i in tqdm(range(lookback_window, len(milk))): x.append(milk[i - lookback_window:i]) y.append(milk[i])
_____no_output_____
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
Generate Array of list x and y
x = np.array(x) y = np.array(y) print(x.shape) print(y.shape)
(156, 12, 1) (156, 1)
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
Model Design
i = Input(shape=(lookback_window, 1)) m = TCN()(i) m = Dense(1, activation='linear')(m) model = Model(inputs=[i], outputs=[m]) model.summary() model.compile('adam','mae')
_____no_output_____
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
Time for Model training...
print('Train...') model.fit(x, y, epochs=100)
Train... Epoch 1/100 5/5 [==============================] - 0s 25ms/step - loss: 271.5721 Epoch 2/100 5/5 [==============================] - 0s 26ms/step - loss: 202.3601 Epoch 3/100 5/5 [==============================] - 0s 23ms/step - loss: 129.1283 Epoch 4/100 5/5 [==============================] - 0s 25ms/step - lo...
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
Prediction with TCN Model
predict = model.predict(x)
_____no_output_____
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
Plot the Result
plt.style.use("fivethirtyeight") plt.figure(figsize = (15,7)) plt.plot(predict) plt.plot(y) plt.title('Monthly Milk Production (in pounds)') plt.legend(['predicted', 'actual']) plt.xlabel("Moths Counts") plt.ylabel("Milk Production in Pounds") plt.show()
_____no_output_____
MIT
TCN_TimeSeries_Approach.ipynb
ashishpatel26/tcn-keras-Examples
synchro.extracting> Function to extract data of an experiment from 3rd party programs To align timeseries of an experiment, we need to read logs and import data produced by 3rd party softwares used during the experiment. It includes:* QDSpy logging* Numpy arrays of the stimuli* SpykingCircus spike sorting refined with...
#export import numpy as np import datetime import os, glob import csv import re from theonerig.synchro.io import * from theonerig.utils import * def get_QDSpy_logs(log_dir): """Factory function to generate QDSpy_log objects from all the QDSpy logs of the folder `log_dir`""" log_names = glob.glob(os.path.join(...
_____no_output_____
Apache-2.0
11_synchro.extracting.ipynb
Ines-Filipa/theonerig
To read QDSpy logs of your experiment, simply provide the folder containing the log you want to read to `get_QDSpy_logs`
#logs = get_QDSpy_logs("./files/basic_synchro")
flickering_bars_pr WARNING dt of frame #15864 was 50.315 m flickering_bars_pr WARNING dt of frame #19477 was 137.235 m
Apache-2.0
11_synchro.extracting.ipynb
Ines-Filipa/theonerig
It returns a list fo the QDSpy logs. Stimuli are contained in a list inside each log:
#logs[0].stimuli
_____no_output_____
Apache-2.0
11_synchro.extracting.ipynb
Ines-Filipa/theonerig
The stimuli objects contains informations on how their display went:
# stim = logs[0].stimuli[5] # print(stim.name, stim.start_time, stim.frame_delay, stim.md5) #export def unpack_stim_npy(npy_dir, md5_hash): """Find the stimuli of a given hash key in the npy stimulus folder. The stimuli are in a compressed version comprising three files. inten for the stimulus values on the scr...
flickering_bars_pr WARNING dt of frame #15864 was 50.315 m flickering_bars_pr WARNING dt of frame #19477 was 137.235 m
Apache-2.0
11_synchro.extracting.ipynb
Ines-Filipa/theonerig
To unpack the stimulus values, provide the folder of the numpy arrays and the hash of the stimulus:
# unpacked = unpack_stim_npy("./files/basic_synchro/stimulus_data", "eed21bda540934a428e93897908d049e")
_____no_output_____
Apache-2.0
11_synchro.extracting.ipynb
Ines-Filipa/theonerig
Unpacked is a tuple, where the first element is the intensity of shape (n_frames, n_colors, y, x)
# unpacked[0].shape
_____no_output_____
Apache-2.0
11_synchro.extracting.ipynb
Ines-Filipa/theonerig
The second element of the tuple repesents the marker values for the timing. QDSpy defaults are zero and ones, but I used custom red squares taking intensities [50,100,150,200,250] to time with five different signals
# unpacked[1][:50]
_____no_output_____
Apache-2.0
11_synchro.extracting.ipynb
Ines-Filipa/theonerig
Each stimulus is also starting with a barcode, of the form:0 0 0 0 0 0 4 0 4\*[1-4] 0 4\*[1-4] 0 4\*[1-4] 0 4\*[1-4] 0 4 0 0 0 0 0 0 and ends with 0 0 0 0 0 0
#export def extract_spyking_circus_results(dir_, record_basename): """Extract the good cells of a record. Overlap with phy_results_dict.""" phy_dir = os.path.join(dir_,record_basename+"/"+record_basename+".GUI") phy_dict = phy_results_dict(phy_dir) good_clusters = [] with open(os.path.join(phy...
Converted 00_core.ipynb. Converted 01_utils.ipynb. Converted 02_processing.ipynb. Converted 03_modelling.ipynb. Converted 04_plotting.ipynb. Converted 05_database.ipynb. Converted 10_synchro.io.ipynb. Converted 11_synchro.extracting.ipynb. Converted 12_synchro.processing.ipynb. Converted 99_testdata.ipynb. Converted in...
Apache-2.0
11_synchro.extracting.ipynb
Ines-Filipa/theonerig
Training a Plant Disease Diagnosis Model with PlantVillage Dataset
import numpy as np import os import matplotlib.pyplot as plt from skimage.io import imread from sklearn.metrics import classification_report, confusion_matrix from sklearn .model_selection import train_test_split import keras import keras.backend as K from keras.preprocessing.image import load_img, img_to_array, Ima...
_____no_output_____
Net-SNMP
notebooks/PlantDisease_tutorial.ipynb
Julia2505/deep_learning_for_biologists
Preparation Data Preparation
!apt-get install subversion > /dev/null #Retreive specifc diseases of tomato for training !svn export https://github.com/spMohanty/PlantVillage-Dataset/trunk/raw/color/Tomato___Bacterial_spot image/Tomato___Bacterial_spot > /dev/null !svn export https://github.com/spMohanty/PlantVillage-Dataset/trunk/raw/color/Tomato...
_____no_output_____
Net-SNMP
notebooks/PlantDisease_tutorial.ipynb
Julia2505/deep_learning_for_biologists
Model Preparation
K.clear_session() nfilter = 32 #VGG16 like model model = Sequential([ #block1 layers.Conv2D(nfilter,(3,3),padding="same",name="block1_conv1",input_shape=(64,64,3)), layers.Activation("relu"), layers.BatchNormalization(), #layers.Dropout(rate=0.2), layers.Conv2D(nfilter,(3,3),padding="...
_____no_output_____
Net-SNMP
notebooks/PlantDisease_tutorial.ipynb
Julia2505/deep_learning_for_biologists
Training
#utilize early stopping function to stop at the lowest validation loss es = EarlyStopping(monitor='val_loss', patience=10, verbose=1, mode='auto') #utilize save best weight model during training ckpt = ModelCheckpoint("PlantDiseaseCNNmodel.hdf5", monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=Fal...
_____no_output_____
Net-SNMP
notebooks/PlantDisease_tutorial.ipynb
Julia2505/deep_learning_for_biologists
Evaluation
#load the model weight file with lowest validation loss model.load_weights("PlantDiseaseCNNmodel.hdf5") #or can obtain the pretrained model from the github repo. #check the model metrics print(model.metrics_names) #evaluate training data print(model.evaluate(x= x_train, y = y_train)) #evaluate validation data print(mo...
_____no_output_____
Net-SNMP
notebooks/PlantDisease_tutorial.ipynb
Julia2505/deep_learning_for_biologists
Predicting Indivisual Images
n = 15 #do not exceed (number of test image - 1) plt.imshow(x_test[n]) plt.show() true_label = np.argmax(y_test,axis=1)[n] print("true_label is:",true_label,":",class_names[true_label]) prediction = model.predict(x_test[n][np.newaxis,...])[0] print("predicted_value is:",prediction) predicted_label = np.argmax(predict...
_____no_output_____
Net-SNMP
notebooks/PlantDisease_tutorial.ipynb
Julia2505/deep_learning_for_biologists
LeNet Lab Solution![LeNet Architecture](lenet.png)Source: Yan LeCun Load DataLoad the MNIST data, which comes pre-loaded with TensorFlow.You do not need to modify this section.
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", reshape=False) X_train, y_train = mnist.train.images, mnist.train.labels X_validation, y_validation = mnist.validation.images, mnist.validation.labels X_test, y_test = mnist.test.images, mn...
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
The MNIST data that TensorFlow pre-loads comes as 28x28x1 images.However, the LeNet architecture only accepts 32x32xC images, where C is the number of color channels.In order to reformat the MNIST data into a shape that LeNet will accept, we pad the data with two rows of zeros on the top and bottom, and two columns of ...
import numpy as np # Pad images with 0s X_train = np.pad(X_train, ((0,0),(2,2),(2,2),(0,0)), 'constant') X_validation = np.pad(X_validation, ((0,0),(2,2),(2,2),(0,0)), 'constant') X_test = np.pad(X_test, ((0,0),(2,2),(2,2),(0,0)), 'constant') print("Updated Image Shape: {}".format(X_train[0].shape))
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
Visualize DataView a sample from the dataset.You do not need to modify this section.
import random import numpy as np import matplotlib.pyplot as plt %matplotlib inline index = random.randint(0, len(X_train)) image = X_train[index].squeeze() plt.figure(figsize=(1,1)) plt.imshow(image, cmap="gray") print(y_train[index])
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
Preprocess DataShuffle the training data.You do not need to modify this section.
from sklearn.utils import shuffle X_train, y_train = shuffle(X_train, y_train)
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
Setup TensorFlowThe `EPOCH` and `BATCH_SIZE` values affect the training speed and model accuracy.You do not need to modify this section.
import tensorflow as tf EPOCHS = 10 BATCH_SIZE = 128
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
SOLUTION: Implement LeNet-5Implement the [LeNet-5](http://yann.lecun.com/exdb/lenet/) neural network architecture.This is the only cell you need to edit. InputThe LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case. Archite...
from tensorflow.contrib.layers import flatten def LeNet(x): # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer mu = 0 sigma = 0.1 # SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6. conv1_W = tf.Variable(tf.trun...
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
Features and LabelsTrain LeNet to classify [MNIST](http://yann.lecun.com/exdb/mnist/) data.`x` is a placeholder for a batch of input images.`y` is a placeholder for a batch of output labels.You do not need to modify this section.
x = tf.placeholder(tf.float32, (None, 32, 32, 1)) y = tf.placeholder(tf.int32, (None)) one_hot_y = tf.one_hot(y, 10)
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
Training PipelineCreate a training pipeline that uses the model to classify MNIST data.You do not need to modify this section.
rate = 0.001 logits = LeNet(x) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits) loss_operation = tf.reduce_mean(cross_entropy) optimizer = tf.train.AdamOptimizer(learning_rate = rate) training_operation = optimizer.minimize(loss_operation)
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
Model EvaluationEvaluate how well the loss and accuracy of the model for a given dataset.You do not need to modify this section.
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1)) accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) saver = tf.train.Saver() def evaluate(X_data, y_data): num_examples = len(X_data) total_accuracy = 0 sess = tf.get_default_session() for offset in ra...
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
Train the ModelRun the training data through the training pipeline to train the model.Before each epoch, shuffle the training set.After each epoch, measure the loss and accuracy of the validation set.Save the model after training.You do not need to modify this section.
with tf.Session() as sess: sess.run(tf.global_variables_initializer()) num_examples = len(X_train) print("Training...") print() for i in range(EPOCHS): X_train, y_train = shuffle(X_train, y_train) for offset in range(0, num_examples, BATCH_SIZE): end = offset + BATCH...
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
Evaluate the ModelOnce you are completely satisfied with your model, evaluate the performance of the model on the test set.Be sure to only do this once!If you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model on the test set a...
with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('.')) test_accuracy = evaluate(X_test, y_test) print("Test Accuracy = {:.3f}".format(test_accuracy))
_____no_output_____
MIT
LeNet-Lab-Solution.ipynb
LiYan1988/LeNet-2
Polynomial Regression What if your data doesn't look linear at all? Let's look at some more realistic-looking page speed / purchase data:
%matplotlib inline from pylab import * import numpy as np np.random.seed(2) pageSpeeds = np.random.normal(3.0, 1.0, 1000) purchaseAmount = np.random.normal(50.0, 10.0, 1000) / pageSpeeds scatter(pageSpeeds, purchaseAmount)
_____no_output_____
MIT
PolynomialRegression.ipynb
Lucian-N/DataScience
numpy has a handy polyfit function we can use, to let us construct an nth-degree polynomial model of our data that minimizes squared error. Let's try it with a 4th degree polynomial:
x = np.array(pageSpeeds) y = np.array(purchaseAmount) p4 = np.poly1d(np.polyfit(x, y, 4))
_____no_output_____
MIT
PolynomialRegression.ipynb
Lucian-N/DataScience
We'll visualize our original scatter plot, together with a plot of our predicted values using the polynomial for page speed times ranging from 0-7 seconds:
import matplotlib.pyplot as plt xp = np.linspace(0, 7, 100) plt.scatter(x, y) plt.plot(xp, p4(xp), c='r') plt.show()
_____no_output_____
MIT
PolynomialRegression.ipynb
Lucian-N/DataScience
Looks pretty good! Let's measure the r-squared error:
from sklearn.metrics import r2_score r2 = r2_score(y, p4(x)) print(r2)
0.82937663963
MIT
PolynomialRegression.ipynb
Lucian-N/DataScience
Single-stepping the `logictools` Pattern Generator * This notebook will show how to use single-stepping mode with the pattern generator* Note that all generators in the _logictools_ library may be **single-stepped** Visually ... The _logictools_ library on the Zynq device on the PYNQ board ![](./images/single-steppin...
# Specify a stimulus waveform and display it from pynq.overlays.logictools import LogicToolsOverlay from pynq.lib.logictools import Waveform logictools_olay = LogicToolsOverlay('logictools.bit') up_counter_stimulus = {'signal': [ {'name': 'bit0', 'pin': 'D0', 'wave': 'lh' * 8}, {'name': 'bit1', 'pin': 'D...
_____no_output_____
BSD-3-Clause
Session_3/3_pattern_generator.ipynb
xupsh/PYNQ_Workshop
Practice: approximate q-learning_Reference: based on Practical RL_ [week04](https://github.com/yandexdataschool/Practical_RL/tree/master/week04_approx_rl)In this notebook you will teach a __pytorch__ neural network to do Q-learning.
# # in google colab uncomment this # import os # os.system('apt-get install -y xvfb') # os.system('wget https://raw.githubusercontent.com/yandexdataschool/Practical_DL/fall18/xvfb -O ../xvfb') # os.system('apt-get install -y python-opengl ffmpeg') # XVFB will be launched if you run on a server import os if type(os.e...
_____no_output_____
MIT
week10_Model_free_learning_peek/practice_approximate_Q_learning.ipynb
GimmeDanger/made_nlp_course
Approximate Q-learning: building the networkTo train a neural network policy one must have a neural network policy. Let's build it.Since we're working with a pre-extracted features (cart positions, angles and velocities), we don't need a complicated network yet. In fact, let's build something like this for starters:![...
import torch import torch.nn as nn import torch.nn.functional as F network = nn.Sequential() network.add_module('layer1', < ... >) <YOUR CODE: stack layers!!!1 > # hint: use state_dim[0] as input size def get_action(state, epsilon=0): """ sample actions with epsilon-greedy policy recap: with p = epsilon ...
_____no_output_____
MIT
week10_Model_free_learning_peek/practice_approximate_Q_learning.ipynb
GimmeDanger/made_nlp_course
Q-learning via gradient descentWe shall now train our agent's Q-function by minimizing the TD loss:$$ L = { 1 \over N} \sum_i (Q_{\theta}(s,a) - [r(s,a) + \gamma \cdot max_{a'} Q_{-}(s', a')]) ^2 $$Where* $s, a, r, s'$ are current state, action, reward and next state respectively* $\gamma$ is a discount factor defined...
def to_one_hot(y_tensor, n_dims=None): """ helper: take an integer vector and convert it to 1-hot matrix. """ y_tensor = y_tensor.type(torch.LongTensor).view(-1, 1) n_dims = n_dims if n_dims is not None else int(torch.max(y_tensor)) + 1 y_one_hot = torch.zeros( y_tensor.size()[0], n_dims).scatte...
_____no_output_____
MIT
week10_Model_free_learning_peek/practice_approximate_Q_learning.ipynb
GimmeDanger/made_nlp_course
Playing the game
opt = torch.optim.Adam(network.parameters(), lr=1e-4) epsilon = 0.5 def generate_session(t_max=1000, epsilon=0, train=False): """play env with approximate q-learning agent and train it at the same time""" total_reward = 0 s = env.reset() for t in range(t_max): a = get_action(s, epsilon=epsilon)...
_____no_output_____
MIT
week10_Model_free_learning_peek/practice_approximate_Q_learning.ipynb
GimmeDanger/made_nlp_course
How to interpret resultsWelcome to the f.. world of deep f...n reinforcement learning. Don't expect agent's reward to smoothly go up. Hope for it to go increase eventually. If it deems you worthy.Seriously though,* __ mean reward__ is the average reward per game. For a correct implementation it may stay low for some 1...
# record sessions import gym.wrappers env = gym.wrappers.Monitor(gym.make("CartPole-v0"), directory="videos", force=True) sessions = [generate_session(epsilon=0, train=False) for _ in range(100)] env.close() # Show video. This may not work in some setups. If it doesn't # work for you, you can...
_____no_output_____
MIT
week10_Model_free_learning_peek/practice_approximate_Q_learning.ipynb
GimmeDanger/made_nlp_course
Frame of reference> Marcos Duarte, Renato Naville Watanabe > [Laboratory of Biomechanics and Motor Control](http://pesquisa.ufabc.edu.br/bmclab) > Federal University of ABC, Brazil Contents1&nbsp;&nbsp;Frame of reference for human motion analysis2&nbsp;&nbsp;Cartesian coordinate system2.1&nbsp;&nbsp;Standardizations...
from IPython.display import IFrame IFrame('https://isbweb.org/activities/standards', width='100%', height=400)
_____no_output_____
CC-BY-4.0
notebooks/ReferenceFrame.ipynb
rnwatanabe/BMC
Another initiative for the standardization of references frames is from the [Virtual Animation of the Kinematics of the Human for Industrial, Educational and Research Purposes (VAKHUM)](https://raw.githubusercontent.com/demotu/BMC/master/refs/VAKHUM.pdf) project. Determination of a coordinate systemIn Biomechanics, w...
import numpy as np m1 = np.array([1, 2, 5]) m2 = np.array([2, 3, 3]) m3 = np.array([4, 0, 2]) v1 = m2 - m1 # first axis v2 = np.cross(v1, m3 - m1) # second axis v3 = np.cross(v1, v2) # third axis # Vector normalization e1 = v1/np.linalg.norm(v1) e2 = v2/np.linalg.norm(v2) e3 = v3/np.linalg.norm...
Versors: e1 = [ 0.40824829 0.40824829 -0.81649658] e2 = [-0.76834982 -0.32929278 -0.5488213 ] e3 = [-0.49292179 0.85141036 0.17924429] Test of orthogonality (cross product between versors): e1 x e2: 1.0 e1 x e3: 1.0000000000000002 e2 x e3: 0.9999999999999999 Norm of each versor: ||e1|| = 1.0 ||e2|| = 1.0 ...
CC-BY-4.0
notebooks/ReferenceFrame.ipynb
rnwatanabe/BMC
To define a coordinate system using the calculated basis, we also need to define an origin. In principle, we could use any point as origin, but if the calculated coordinate system should follow anatomical conventions, e.g., the coordinate system origin should be at a joint center, we will have to calculate the basis an...
origin = np.mean((m1, m2, m3), axis=0) print('Origin: ', origin)
Origin: [2.33333333 1.66666667 3.33333333]
CC-BY-4.0
notebooks/ReferenceFrame.ipynb
rnwatanabe/BMC
Let's plot the coordinate system and the basis using the custom Python function `CCS.py`:
import sys sys.path.insert(1, r'./../functions') # add to pythonpath from CCS import CCS markers = np.vstack((m1, m2, m3)) basis = np.vstack((e1, e2, e3))
_____no_output_____
CC-BY-4.0
notebooks/ReferenceFrame.ipynb
rnwatanabe/BMC
Create figure in this page (inline):
%matplotlib notebook markers = np.vstack((m1, m2, m3)) basis = np.vstack((e1, e2, e3)) CCS(xyz=[], Oijk=origin, ijk=basis, point=markers, vector=True);
_____no_output_____
CC-BY-4.0
notebooks/ReferenceFrame.ipynb
rnwatanabe/BMC
Gram–Schmidt processAnother classical procedure in mathematics, employing the scalar product, is known as the [Gram–Schmidt process](http://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process). See the notebook [Scalar and Vector](http://nbviewer.jupyter.org/github/bmclab/BMC/blob/master/notebooks/ScalarVector.ipynb) f...
import numpy as np a = np.array([1, 2, 0]) b = np.array([0, 1, 3]) c = np.array([1, 0, 1])
_____no_output_____
CC-BY-4.0
notebooks/ReferenceFrame.ipynb
rnwatanabe/BMC
The first versor is:
ea = a/np.linalg.norm(a) print(ea)
[ 0.4472136 0.89442719 0. ]
CC-BY-4.0
notebooks/ReferenceFrame.ipynb
rnwatanabe/BMC
The second versor is:
eb = b - np.dot(b, ea)*ea eb = eb/np.linalg.norm(eb) print(eb)
[-0.13187609 0.06593805 0.98907071]
CC-BY-4.0
notebooks/ReferenceFrame.ipynb
rnwatanabe/BMC
And the third version is:
ec = c - np.dot(c, ea)*ea - np.dot(c, eb)*eb ec = ec/np.linalg.norm(ec) print(ec)
[ 0.88465174 -0.44232587 0.14744196]
CC-BY-4.0
notebooks/ReferenceFrame.ipynb
rnwatanabe/BMC
Let's check the orthonormality between these versors:
print(' Versors:', '\nea =', ea, '\neb =', eb, '\nec =', ec) print('\n Test of orthogonality (scalar product between versors):', '\n ea x eb:', np.dot(ea, eb), '\n eb x ec:', np.dot(eb, ec), '\n ec x ea:', np.dot(ec, ea)) print('\n Norm of each versor:', '\n ||ea|| =', np.linalg.norm(ea), ...
Versors: ea = [ 0.4472136 0.89442719 0. ] eb = [-0.13187609 0.06593805 0.98907071] ec = [ 0.88465174 -0.44232587 0.14744196] Test of orthogonality (scalar product between versors): ea x eb: 2.08166817117e-17 eb x ec: -2.77555756156e-17 ec x ea: 5.55111512313e-17 Norm of each versor: ||ea|| ...
CC-BY-4.0
notebooks/ReferenceFrame.ipynb
rnwatanabe/BMC
Volume Sampling vs projection DPP for low rank approximation Introduction In this notebook we compare the volume sampling and projection DPP for low rank approximation.We recall the result proved in the article [DRVW]:\\Let S be a random subset of k columns of X chosen with probability: $$P(S) = \frac{1}{Z_{k}} det(X_...
import numpy as np import pandas as pd from itertools import combinations from scipy.stats import binom import scipy.special import matplotlib.pyplot as plt import matplotlib.patches as mpatches from IPython.display import display, HTML from FrameBuilder.eigenstepsbuilder import * from decimal import * u = np.random.un...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
I-1- Givens Rotations generatorsThese functions generate a Givens rotation
def t_func(q_i,q_j,q_ij,l_i,l_j): # t in section 3.1 Dhillon (2005) delta = np.power(q_ij,2)-(q_i-l_i)*(q_j-l_i) if delta<0: print(delta) print("error sqrt") t = q_ij - np.sqrt(delta) t = t/(q_j-l_i) return t def G_func(i,j,q_i,q_j,q_ij,l_i,l_j,N): # Gitens Rotation...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
The following function is an implementation of the algorithm [] figuring in the article [] to generate an orthogonal matrix with a prescribed profile of leverage scores.In fact this is a simplification of the algorithm .....
class Data_Set_Generator: def __init__(self, N, d, nu, Sigma): self.N = N self.d = d self.nu = nu self.Sigma = Sigma self.mean = np.zeros(d) def multivariate_t_rvs(self): x = np.random.chisquare(self.nu, self.N)/self.nu z = np.random.multivariate_...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
The following function allows to estimate the leverage scores for an orthogonal matrix Q: the function calculates the diagonoal of the matrix $$Q Q^{T}$$
def estimate_leverage_scores_from_orthogonal_matrix(Q): [N,_] = np.shape(Q) lv_scores_vector = np.zeros((N,1)) lv_scores_vector = np.diag(np.dot(Q,np.transpose(Q))) lv_scores_vector = np.asarray(list(reversed(np.sort(lv_scores_vector)))) return lv_scores_vector def estimate_sum_first_k_leverage_scor...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
I-2- Extending the orthogonal matrices For the task of low rank approximation, we have seen that only the information contained in the first right k eigenvectors of the matrix X are relevant. In the previous step we build only the first right k eigenvectors but we still need to complete these orthogonal matrices with ...
def extend_orthogonal_matrix(Q,d_target): [N,d] = np.shape(Q) Q_target = np.zeros((N,d)) Q_target = Q delta = d_target - d for t in range(delta): Q_test = np.random.normal(0, 1, N) for _ in range(d): Q_test = Q_test - np.dot(Q_test,Q[:,_])*Q[:,_] Q_test = Q_test/n...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
I-3 - Constructing a dataset for every extended orthogonal matrix The previous step allow us to build (N x d) orthogonal matrices such that the extracted (N x k) matrix have a prescribed profile of leverage scores.Now we construct a cloud of point by assigning a covariance matrix D and a matrix V
def contruct_dataset_from_orthogonal_matrix(multi_Q,N,target_d,cov,mean,versions_number): multi_X = np.zeros((versions_number+1,N,real_dim)) for t in range(versions_number+1): test_X = np.random.multivariate_normal(mean, cov, N) [U,_,_] = np.linalg.svd(test_X, full_matrices=False) Q_test...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
II- Volume sampling vs Projection DPP for low rank approximationThese functions allow to quantify the approximation error:* approximation_error_function_fro calculate the ratio of the approximation error of a subset of columns to the optimal approximatione error given by the first k left eigenvectors of the matrix X* ...
def approximation_error_function_fro(Sigma,k,X,X_S): ## Sigma is the spectrum of the matrix X: we need to calculate the optimal approximation error given by the PCA ## k is the rank of the approximation ## X is the initial matrix ## X_S is the subset of columns of the matrix X for witch we calculate the...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
III - Numerical analysis In this section we use the functions developed previously to investigate the influence of two parameters: the spectrum of X and the k-leverage scores. For this purpose, we assemble these functionalities in a class allowing fast numerical experiments.
class Numrerical_Analysis_DPP: def __init__(self,N,real_dim,r,k,versions_number,mean,cov,lv_scores,versions_list): self.N = N self.real_dim = real_dim self.r = r self.k = k self.versions_number = versions_number self.mean = mean self.cov = cov self.lv...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
III- 0 Parameters of the simultations
## The dimensions of the design matrix X N = 100 # The number of observations in the dataset real_dim = 20 # The dimension of the dataset ## The low rank paramters k = 2 # The rank of the low rank approximation ## The covariance matrix parameters r = 6 # Just a parameter to control the number of ...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
III-1 The influence of the spectrum In this subsection we compare the Volume Sampling distribution to the projection DPP distribution and the deterministic algorithm of [] for different profiles of the spectrum with k-leverage scores profile fixed. In other words, if we note $$X = UDV^{T}$$ We keep V_{k} constant and...
cov_1 = np.diag(np.concatenate(([100,100,1,1,1,1],cov_test))) versions_list = [20,19,18,17] NAL_1 = Numrerical_Analysis_DPP(N,real_dim,r,k,versions_number,mean,cov_1,lv_scores_vector,versions_list) projection_DPP_res_fro_1 = NAL_1.get_expected_error_fro_for_projection_DPP() volume_sampling_res_fro_1 = NAL_1.get_expec...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder