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
GradCAM action happens hereAdapting from https://keras.io/examples/vision/grad_cam/
import tensorflow as tf last_conv_layer_name = "conv1d_23" classifier_layer_names = [ "batch_normalization_23", "activation_23", "max_pooling1d_23", "flatten_5", "dense_5", "dropout_5", "Output_Classes" ] def make_gradcam_heatmap( img_array, model, last_conv_layer_name, classifier_layer_names ): # First, we cre...
_____no_output_____
MIT
cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb
divijsharma18/timedomain
Apply GradCAM to all spectra classified as transients
#allzbest = allzbest[1:] #TEMP #allzbest.pprint_all() #print(labels.shape) #print(labels) #print(rewave.shape) #print(rsflux.shape) preprocess_input = keras.applications.xception.preprocess_input decode_predictions = keras.applications.xception.decode_predictions # Loop over all and create a bunch of 16x16 plots fig,...
_____no_output_____
MIT
cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb
divijsharma18/timedomain
Plot spectra of objects classified as transientsPlot observed spectra
testwave, testflux, testivar = rebin_flux(allwave, allflux, allivar, minwave=2500., maxwave=9500., nbins=150, log=True, clip=True) fig, axes = plt.subplots(4,4, figsize=(15,10), sharex=True, sharey=True, gridspec_kw={'wspac...
_____no_output_____
MIT
cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb
divijsharma18/timedomain
For plotting individual plots
# Save to FITS files rather than PNG, see cnn_classify_data.py # See line 404 - 430, 'Save Classification info to file' #https://github.com/desihub/timedomain/blob/ab7257a4ed232875f5769cbb11c21f483ceccc5e/cronjobs/cnn_classify_data.py#L404 for j in selection: plt.plot(testwave, testflux[j[0]], alpha=0.7, label='la...
_____no_output_____
MIT
cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb
divijsharma18/timedomain
Reading files in parallelDoes not work
# Loop through zbest and coadd files for each petal. # Extract the fibermaps, ZBEST tables, and spectra. # Keep only BGS targets passing basic event selection. allzbest = None allfmap = None allwave = None allflux = None allivar = None allmask = None allres = None handy_table = [] from joblib import Parallel, delayed...
_____no_output_____
MIT
cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb
divijsharma18/timedomain
Matplotlib - Gráfico de superfície 3D * Criando gráficos de scatter 3D com a biblioteca MatPlotLib * Importando bibliotecas
import numpy as np import matplotlib.pyplot as plt
_____no_output_____
MIT
Data_Science/Matplotlib/3D/3D_Superficie.ipynb
maledicente/cursos
* Criando variáveis X e Y
X = np.linspace(-5,5,11) Y = np.linspace(-5,5,11)
_____no_output_____
MIT
Data_Science/Matplotlib/3D/3D_Superficie.ipynb
maledicente/cursos
* Convertendo variáveis X e Y para malha
X, Y = np.meshgrid(X, Y)
_____no_output_____
MIT
Data_Science/Matplotlib/3D/3D_Superficie.ipynb
maledicente/cursos
* Criando variável Z
Z = X**2 + Y**2
_____no_output_____
MIT
Data_Science/Matplotlib/3D/3D_Superficie.ipynb
maledicente/cursos
* Gráfico 3D
from matplotlib import cm from mpl_toolkits.mplot3d import axes3d fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(X,Y,Z) ax.set_xlabel('Eixo X') ax.set_ylabel('Eixo Y') ax.set_zlabel('Eixo Z') plt.tight_layout() plt.show()
_____no_output_____
MIT
Data_Science/Matplotlib/3D/3D_Superficie.ipynb
maledicente/cursos
* Usando mapa de cores
fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(X,Y,Z, cmap=cm.coolwarm, antialiased=False) ax.set_xlabel('Eixo X') ax.set_ylabel('Eixo Y') ax.set_zlabel('Eixo Z') plt.tight_layout() plt.show()
_____no_output_____
MIT
Data_Science/Matplotlib/3D/3D_Superficie.ipynb
maledicente/cursos
* Barra de cores
fig = plt.figure() ax = fig.gca(projection='3d') surf = ax.plot_surface(X,Y,Z, cmap=cm.coolwarm, antialiased=False) ax.set_xlabel('Eixo X') ax.set_ylabel('Eixo Y') ax.set_zlabel('Eixo Z') fig.colorbar(surf, shrink=0.5, aspect=5) plt.tight_layout() plt.show()
_____no_output_____
MIT
Data_Science/Matplotlib/3D/3D_Superficie.ipynb
maledicente/cursos
Ranking, Regression, Classification
%%time import lightgbm from project.ranker.ltr_rankers import cv_lgbm from sklearn.model_selection import RepeatedKFold kfolds = RepeatedKFold(10, n_repeats=2, random_state=42) params = {'objective': 'lambdarank', 'metric': 'ndcg', 'learning_rate': 1e-3, # 'num_leaves': 50, 'nd...
Fold 1 | #Est: 1 | Trn_Spearman: -0.0954 | Val_Spearman: 0.0375 | Trn_ACCLoss: 0.1136 | Val_ACCLoss: 0.1499 | Trn_NDCG: 0.5295 | Val_NDCG: 0.5097 Fold 2 | #Est: 1 | Trn_Spearman: -0.0900 | Val_Spearman: -0.0110 | Trn_ACCLoss: 0.1129 | Val_ACCLoss: 0.1561 | Trn_NDCG: 0.5317 | Val_NDCG: 0.4901 Fold 3 |...
MIT
matrix_factorization/04 - LambdaRank.ipynb
Howl24/fs-ranking-prediction
10 runs - 10 folds
%%time import lightgbm from project.ranker.ltr_rankers import cv_lgbm from sklearn.model_selection import RepeatedKFold kfolds = RepeatedKFold(10, n_repeats=10, random_state=42) params = {'objective': 'lambdarank', 'metric': 'ndcg', 'learning_rate': 1e-3, # 'num_leaves': 50, 'n...
_____no_output_____
MIT
matrix_factorization/04 - LambdaRank.ipynb
Howl24/fs-ranking-prediction
New ranking
%%time from sklearn.model_selection import train_test_split rp = Pipeline([ ('scale', StandardScaler()), ('estimator', RankingPredictor("ma_100", n_neighbors=15)), ]) df_mf, df_rank, df_scores, _ = rp.named_steps['estimator'].get_data() df_mf = df_mf.sort_index() df_rank = df_rank.sort_index() df_scores = df_s...
_____no_output_____
MIT
matrix_factorization/04 - LambdaRank.ipynb
Howl24/fs-ranking-prediction
There are ```70,000``` images of size ```28 x 28``` in flattened form
pixel_values.shape
_____no_output_____
MIT
tSNE.ipynb
FelixArokia/AAAML
Viewing the first image
pixel_values[0, :].shape single_image = pixel_values[0, :] single_image = single_image.reshape(28,28) single_image.shape plt.imshow(single_image, cmap = 'gray')
_____no_output_____
MIT
tSNE.ipynb
FelixArokia/AAAML
tSNE
tsne = manifold.TSNE(n_components=2, random_state=42) transformed_data = tsne.fit_transform(pixel_values[:3000, :]) transformed_data transformed_data.shape tsne = np.column_stack(transformed_data) tsne.shape print('transformed_data shape: ', transformed_data.shape) print('targets shape : ', targets[:3000].shape...
_____no_output_____
MIT
tSNE.ipynb
FelixArokia/AAAML
sns visuals
grid = sns.FacetGrid(tsne_df, hue="targets", size=8) grid.map(plt.scatter, "d1", "d2").add_legend()
/Users/felix/.pyenv/versions/3.6.9/lib/python3.6/site-packages/seaborn/axisgrid.py:316: UserWarning: The `size` parameter has been renamed to `height`; please update your code. warnings.warn(msg, UserWarning)
MIT
tSNE.ipynb
FelixArokia/AAAML
Altair visuals
import altair as alt source = tsne_df source['targets'] = source['targets'].astype(str) alt.Chart(source).mark_circle().encode( alt.X('d1', scale=alt.Scale(zero=False)), alt.Y('d2', scale=alt.Scale(zero=False, padding=1)), color='targets' ) ### how to get cluster id from tsne ?
_____no_output_____
MIT
tSNE.ipynb
FelixArokia/AAAML
# Create a text file, or copy the code snippets into a Python file #1 def a(): return 5 print(a()) #2 def a(): return 5 print(a()+a()) #3 def a(): return 5 return 10 print(a()) #4 def a(): return 5 print(10) print(a()) #5 def a(): print(5) x = a() print(x) #6 ...
7 14 21
Apache-2.0
basicFun.ipynb
helah20/Python
ALS
model = implicit.als.AlternatingLeastSquares(factors=16, regularization=0.0, iterations=8) model.fit(X_sparse.T) # обязательный шаг m_ap = [] for js in tqdm(valid_data): row_sparse = make_coo_row(js["transaction_history"], product_encoder).tocsr() raw_recs = model.recommend(0, row_sparse, N=30, filter_already_...
_____no_output_____
MIT
sandbox/2.1.als.ipynb
dmitrii-davidov/retailhero-recomender-baseline
Codebuster STAT 535 Statistical Computing Project Movie recommendation recommendation pipeline Patrick's comments 11/9- Goal: Build a small real world deployment pipeline like it can be used in netflix / amazon - build / test with movie recommendation data set (model fitting, data preprocessing, evaluation)- Show tha...
import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline from scipy import interp from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import GradientBoostingClassifier from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import linear...
_____no_output_____
Apache-2.0
tobi.ipynb
tobikuhlmann/Movie-recommendation-lab
Data Understanding and PreprocessingGet a feeling for the dataset, its problems and conduct helpful preprocessing
df = pd.read_csv("allData.tsv", sep='\t') print(f"Shape: {df.shape}") print(df.dtypes) df.head() df.age.value_counts()
_____no_output_____
Apache-2.0
tobi.ipynb
tobikuhlmann/Movie-recommendation-lab
Histogram: Number of movies are rated by usersMost users rated only up tp 5 movies
df.userID.value_counts().hist(bins=50)
_____no_output_____
Apache-2.0
tobi.ipynb
tobikuhlmann/Movie-recommendation-lab
Divide datasets for different recommendations (random forest, content based, collaborative based)It can be useful to use content-based recommender systems for those users
df_split = df.copy() df_split.set_index('userID', inplace=True) # set for content based recommendation with #ratings < 10 df_content = df_split[df.userID.value_counts()<10] # set for collaborative recommendation with #ratings >= 10 df_collaborative = df_split[df.userID.value_counts()>=10] df_content.index.value_counts...
_____no_output_____
Apache-2.0
tobi.ipynb
tobikuhlmann/Movie-recommendation-lab
Transform numerical rating to binary- 1, if user rates movie 4 or 5- 0, if user rates movie less than 4
df['rating'].mask(df['rating'] < 4, 0, inplace=True) df['rating'].mask(df['rating'] > 3, 1, inplace=True)
_____no_output_____
Apache-2.0
tobi.ipynb
tobikuhlmann/Movie-recommendation-lab
Check rating distribution
df['rating'].hist()
_____no_output_____
Apache-2.0
tobi.ipynb
tobikuhlmann/Movie-recommendation-lab
Recommendation Cold start: Gradient Boosting ClassifierLogic: Treat every user as same, predicting rating over whole movie dataset - Case 0 rated movies: Supervised prediction with just user age, gender, and year of the movieIn case of cold-start: No user information available
# Cross Validation to test and anticipate overfitting problem def crossvalidate(clf, X,y): ''' Calculate precision, recall, and roc_auc for a 10-fold cross validation run with passed classifier ''' scores1 = cross_val_score(clf, X, y, cv=10, scoring='precision') scores2 = cross_val_score(clf, X, y, ...
_____no_output_____
Apache-2.0
tobi.ipynb
tobikuhlmann/Movie-recommendation-lab
Preprocessing for boosted random forest classifier
# User information before any movie ratings X = df[['age', 'gender', 'year', 'genre1', 'genre2', 'genre3']] y = df['rating'].as_matrix() # Preprocessing # One hot encoding dummyvars = pd.get_dummies(X[['gender', 'genre1', 'genre2', 'genre3']]) # append the dummy variables to df X = pd.concat([X[['age', 'year']], dummy...
_____no_output_____
Apache-2.0
tobi.ipynb
tobikuhlmann/Movie-recommendation-lab
Content-based recommendation with tf-idf for user with <10 ratings- Case < 10 rated movies: Content-based recommender systemContent-based recommendation information about users and their taste. As we can see in the preprocessing, most of the users only rated one to five movies, implying that we have incomplete user-p...
# import movies movies = pd.read_csv("movies.tsv", sep='\t') print(f"Shape: {df.shape}") movies.head() # Preprocessing # Strip space at the end of string movies['name'] = movies['name'].str.rstrip() # Concat genres into one string movies['genres_concat'] = movies[['genre1', 'genre2', 'genre3']].astype(str).apply(' '.jo...
_____no_output_____
Apache-2.0
tobi.ipynb
tobikuhlmann/Movie-recommendation-lab
Test recommendations
content_based_recommendation(movies, 'Father of the Bride Part II', 5)
_____no_output_____
Apache-2.0
tobi.ipynb
tobikuhlmann/Movie-recommendation-lab
Calculate performance of kWIP=============================The next bit of python code calculates the performance of kWIP against the distance between samples calulcated from the alignments of their genomes.This code caluclates spearman's $\rho$ between the off-diagonal elements of the triagnular distance matrices.
expts = list(map(lambda fp: path.basename(fp.rstrip('/')), glob('data/*/'))) print("Expts:", *expts[:10], "...") def process_expt(expt): expt_results = [] def extract_info(filename): return re.search(r'kwip/(\d\.?\d*)x-(0\.\d+)-(wip|ip).dist', filename).groups() # dict of scale: distance m...
_____no_output_____
MIT
writeups/coalescent/100runs_2016-04-26/analysis.ipynb
kdmurray91/kwip-experiments
Statistical analysis====================Is done is R, as that's easier.Below we see a summary and structure of the data
%%R -i results results$coverage = as.numeric(as.character(results$coverage)) results$scale = as.numeric(as.character(results$scale)) print(summary(results)) str(results)
_____no_output_____
MIT
writeups/coalescent/100runs_2016-04-26/analysis.ipynb
kdmurray91/kwip-experiments
Experiment designBelow we see the design of the experiment in terms of the two major variables.We have a series (vertically) that, at 30x coverage, looks at the effect of genetic variation on performance. There is a second series that examines the effect of coverage at an average pairwise genetic distance of 0.001.The...
%%R ggplot(results, aes(x=coverage, y=scale)) + geom_point() + scale_x_log10() + scale_y_log10() + theme_bw()
_____no_output_____
MIT
writeups/coalescent/100runs_2016-04-26/analysis.ipynb
kdmurray91/kwip-experiments
Effect of Coverage------------------Here we show the spread of data across the 100 reps as boxplots per metric and covreage level.I note that the weighted product seems slightly more variable, particularly at higher coverage. Though the median is nearly always higher
%%R dat = results %>% filter(scale==0.001, coverage<=30) %>% select(rho, metric, coverage) dat$coverage = as.factor(dat$coverage) ggplot(dat, aes(x=coverage, y=rho, fill=metric)) + geom_boxplot(aes(fill=metric)) %%R # AND AGAIN WITHOUT SUBSETTING dat = results %>% filter(scale==0...
_____no_output_____
MIT
writeups/coalescent/100runs_2016-04-26/analysis.ipynb
kdmurray91/kwip-experiments
Example from Image Processing
%matplotlib inline import matplotlib.pyplot as plt
_____no_output_____
CC0-1.0
notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb
mottiden/scipy_2015_sklearn_tutorial-master
Here we'll take a look at a simple facial recognition example.This uses a dataset available within scikit-learn consisting of asubset of the [Labeled Faces in the Wild](http://vis-www.cs.umass.edu/lfw/)data. Note that this is a relatively large download (~200MB) so it maytake a while to execute.
from sklearn import datasets lfw_people = datasets.fetch_lfw_people(min_faces_per_person=70, resize=0.4, data_home='datasets') lfw_people.data.shape
_____no_output_____
CC0-1.0
notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb
mottiden/scipy_2015_sklearn_tutorial-master
If you're on a unix-based system such as linux or Mac OSX, these shell commandscan be used to see the downloaded dataset:
!ls datasets !du -sh datasets/lfw_home
_____no_output_____
CC0-1.0
notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb
mottiden/scipy_2015_sklearn_tutorial-master
Once again, let's visualize these faces to see what we're working with:
fig = plt.figure(figsize=(8, 6)) # plot several images for i in range(15): ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) ax.imshow(lfw_people.images[i], cmap=plt.cm.bone) import numpy as np plt.figure(figsize=(10, 2)) unique_targets = np.unique(lfw_people.target) counts = [(lfw_people.target == i).su...
_____no_output_____
CC0-1.0
notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb
mottiden/scipy_2015_sklearn_tutorial-master
One thing to note is that these faces have already been localized and scaledto a common size. This is an important preprocessing piece for facialrecognition, and is a process that can require a large collection of trainingdata. This can be done in scikit-learn, but the challenge is gathering asufficient amount of tra...
from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split( lfw_people.data, lfw_people.target, random_state=0) print(X_train.shape, X_test.shape)
_____no_output_____
CC0-1.0
notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb
mottiden/scipy_2015_sklearn_tutorial-master
Preprocessing: Principal Component Analysis 1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 features to a manageablesize, while maintaining most of the information in the dataset. Here it is useful to use a variantof PCA called ``RandomizedPCA``, which is an approximation of PCA that can be muc...
from sklearn import decomposition pca = decomposition.RandomizedPCA(n_components=150, whiten=True, random_state=1999) pca.fit(X_train) X_train_pca = pca.transform(X_train) X_test_pca = pca.transform(X_test) print(X_train_pca.shape) print(X_test_pca.shape)
_____no_output_____
CC0-1.0
notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb
mottiden/scipy_2015_sklearn_tutorial-master
These projected components correspond to factors in a linear combination ofcomponent images such that the combination approaches the original face. In general, PCA can be a powerful technique for preprocessing that can greatly improve classification performance. Doing the Learning: Support Vector Machines Now we'll pe...
from sklearn import svm clf = svm.SVC(C=5., gamma=0.001) clf.fit(X_train_pca, y_train)
_____no_output_____
CC0-1.0
notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb
mottiden/scipy_2015_sklearn_tutorial-master
Finally, we can evaluate how well this classification did. First, we might plot afew of the test-cases with the labels learned from the training set:
fig = plt.figure(figsize=(8, 6)) for i in range(15): ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) ax.imshow(X_test[i].reshape((50, 37)), cmap=plt.cm.bone) y_pred = clf.predict(X_test_pca[i])[0] color = 'black' if y_pred == y_test[i] else 'red' ax.set_title(lfw_people.target_names[y_pred],...
_____no_output_____
CC0-1.0
notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb
mottiden/scipy_2015_sklearn_tutorial-master
The classifier is correct on an impressive number of images given the simplicityof its learning model! Using a linear classifier on 150 features derived fromthe pixel-level data, the algorithm correctly identifies a large number of thepeople in the images.Again, we canquantify this effectiveness using ``clf.score``
print(clf.score(X_test_pca, y_test))
_____no_output_____
CC0-1.0
notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb
mottiden/scipy_2015_sklearn_tutorial-master
1)Which of the following operators is used to calculate remainder in a division? ANS-%
## 2) 2/3 ## 3)_ 6<<2 ## 4) 6&2 ## 5) 6|2
_____no_output_____
Apache-2.0
Assignment 1.ipynb
benarutochan/Internship-22-
6)What does the finally keyword denotes in python? ANS-the finally block will be executed no matter if the try block raises an error or not. 7)What does raise keyword is used for in python? ANS-A) It is used to raise an exception. 8)Which of the following is a common use case of yield keyword in python? ANS...
## For factors def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) n=int(input("Input a number to compute the factiorial : ")) print(factorial(n))
Input a number to compute the factiorial : 7 5040
Apache-2.0
Assignment 1.ipynb
benarutochan/Internship-22-
12) Write a python program to find whether a number is prime or composite.
num = int(input("Enter any number : ")) if num > 1: for i in range(2, num): if (num % i) == 0: print(num, "is NOT a prime number") break else: print(num, "is a PRIME number") elif num == 0 or 1: print(num, "is a neither prime NOR composite number") else: print(num...
Enter any number : 15 15 is NOT a prime number
Apache-2.0
Assignment 1.ipynb
benarutochan/Internship-22-
13)Write a python program to check whether a given string is palindrome or not.
num=int(input("Enter a number:")) temp=num rev=0 while(num>0): dig=num%10 rev=rev*10+dig num=num//10 if(temp==rev): print("The number is palindrome!") else: print("Not a palindrome!") ## for both number and alphabet which are pallindrome. string=input(("Enter a string:")) if(string==string[::-1]): ...
Enter a string:123456787654321 The string is a palindrome
Apache-2.0
Assignment 1.ipynb
benarutochan/Internship-22-
14)Write a Python program to get the third side of right-angled triangle from two given sides.
def pythagoras(opposite_side,adjacent_side,hypotenuse): if opposite_side == str("x"): return ("Opposite = " + str(((hypotenuse**2) - (adjacent_side**2))**0.5)) elif adjacent_side == str("x"): return ("Adjacent = " + str(((hypotenuse**2) - (opposite_side**2))**0.5)) elif h...
_____no_output_____
Apache-2.0
Assignment 1.ipynb
benarutochan/Internship-22-
15) Write a python program to print the frequency of each of the characters present in a given string.
def char_frequency(str1): dict = {} for n in str1: keys = dict.keys() if n in keys: dict[n] += 1 else: dict[n] = 1 return dict print(char_frequency('lord of the ring and games of thrones'))
{'l': 1, 'o': 4, 'r': 3, 'd': 2, ' ': 7, 'f': 2, 't': 2, 'h': 2, 'e': 3, 'i': 1, 'n': 3, 'g': 2, 'a': 2, 'm': 1, 's': 2}
Apache-2.0
Assignment 1.ipynb
benarutochan/Internship-22-
Putting It All TogetherAs you might have guessed from the last notebook, using all of the variables was allowing you to drastically overfit the training data. This was great for looking good in terms of your Rsquared on these points. However, this was not great in terms of how well you were able to predict on the te...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error import AllTogether as t import seaborn as sns %matplotlib inline df = pd.read_csv('./sur...
_____no_output_____
MIT
Lesson_2_Introduction/1.9 Putting It All Together.ipynb
ReemAlattas/DSND
Question 1**1.** To begin fill in the format function below with the correct variable. Notice each **{ }** holds a space where one of your variables will be added to the string. This will give you something to do while the the function does all the steps you did throughout this lesson.
a = 'test_score' b = 'train_score' c = 'linear model (lm_model)' d = 'X_train and y_train' e = 'X_test' f = 'y_test' g = 'train and test data sets' h = 'overfitting' q1_piat = '''In order to understand how well our {} fit the dataset, we first needed to split our data into {}. Then we were a...
This one is tricky - here is the order of the letters for the solution we had in mind: c, g, c, d, c, e, f, b, a, h
MIT
Lesson_2_Introduction/1.9 Putting It All Together.ipynb
ReemAlattas/DSND
Question 2**2.** Now, we need to improve the model . Use the dictionary below to provide the true statements about improving **this model**. **Also consider each statement as a stand alone**. Though, it might be a good idea after other steps, which would you consider a useful **next step**?
a = 'yes' b = 'no' q2_piat = {'add interactions, quadratics, cubics, and other higher order terms': b, 'fit the model many times with different rows, then average the responses': a, 'subset the features used for fitting the model each time': a, 'this model is hopeless, we should start...
Nice job! That looks right! These two techniques are really common in Machine Learning algorithms to combat overfitting. Though the first technique could be useful, it is not likely to help us right away with our current model. These additional features would likely continue to worsen the nature of overfitting we ar...
MIT
Lesson_2_Introduction/1.9 Putting It All Together.ipynb
ReemAlattas/DSND
Question 3**3.** Before we get too far along, follow the steps in the function below to create the X (explanatory matrix) and y (response vector) to be used in the model. If your solution is correct, you should see a plot similar to the one shown in the Screencast.
def clean_data(df): ''' INPUT df - pandas dataframe OUTPUT X - A matrix holding all of the variables you want to consider when predicting the response y - the corresponding response vector This function cleans df using the following steps to produce X and y: 1. Drop all the ro...
_____no_output_____
MIT
Lesson_2_Introduction/1.9 Putting It All Together.ipynb
ReemAlattas/DSND
Question 4**4.** Use the output and above plot to correctly fill in the keys of the **q4_piat** dictionary with the correct variable. Notice that only the optimal model results are given back in the above - they are stored in **lm_model**, **X_train**, **X_test**, **y_train**, and **y_test**. If more than one answer...
print(X_train.shape[1]) #Number of columns print(r2_scores_test[np.argmax(r2_scores_test)]) # The model we should implement test_r2 print(r2_scores_train[np.argmax(r2_scores_test)]) # The model we should implement train_r2 a = 'we would likely have a better rsquared for the test data.' b = 1000 c = 872 d = 0.69 e = 0....
Nice job! That looks right! We can see that the model we should impement was the 6th model using 1088 features. It is the model that has the best test rsquared value.
MIT
Lesson_2_Introduction/1.9 Putting It All Together.ipynb
ReemAlattas/DSND
Question 5**5.** The default penalty on coefficients using linear regression in sklearn is a ridge (also known as an L2) penalty. Because of this penalty, and that all the variables were normalized, we can look at the size of the coefficients in the model as an indication of the impact of each variable on the salary....
def coef_weights(coefficients, X_train): ''' INPUT: coefficients - the coefficients of the linear model X_train - the training data, so the column names can be used OUTPUT: coefs_df - a dataframe holding the coefficient, estimate, and abs(estimate) Provides a dataframe that can be used...
Nice job! That looks right! The country and years of experience both seem to have a significant impact on the salary of individuals.
MIT
Lesson_2_Introduction/1.9 Putting It All Together.ipynb
ReemAlattas/DSND
Automatic gradient derivation
x = torch.ones(2, 2, requires_grad=True) print(x) y = x + 2 print(y) print(y.grad_fn) z = y*y*3 out = z.mean() print(z) print(out) # gradients out.backward() print(x.grad) print(x) c = torch.ones(2, 2, requires_grad=True) d = c.sum() d.backward() print(c.grad) x = torch.randn(3, requires_grad=True) y = x * 2 while y...
tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [2.0494, 1.9833, 1.0673, 1.3994, 2.4251], [4.0988, 3.9666, 2.1346, 2.7987, 4.8503], [6.1483, 5.9499, 3.2020, 4.1981, 7.2754], [8.1977, 7.9332, 4.2693, 5.5974, 9.7005]])
MIT
models/RL_Course_Aalto/Torch testing _introduction.ipynb
maxmax1992/Deep_RL
Simple full layer neural network Example
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import math import torch from torch.optim import Optimizer class Adam(Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False): if not 0.0 <= ...
_____no_output_____
MIT
models/RL_Course_Aalto/Torch testing _introduction.ipynb
maxmax1992/Deep_RL
Fourier Transforms
import numpy as np from scipy.integrate import quad import matplotlib.pyplot as plt
_____no_output_____
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Part 1: The Discrete Fourier Transform We’re about to make the transition from Fourier series to the Fourier transform. “Transition” is theappropriate word, for in the approach we’ll take the Fourier transform emerges as we pass from periodicto nonperiodic functions. To make the trip we’ll view a nonperiodic function ...
def pulseFunction(x): return 1/(3 + (x-20)**2) x = np.linspace(-10, 50, 200) plt.plot(x, pulseFunction(x)) plt.plot(np.zeros(100), np.linspace(0, 0.5, 100), "--") plt.plot(np.ones(100) *40, np.linspace(0, 0.5, 100), "--") plt.show()
_____no_output_____
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Step 1: Periodic Pulse Function Take the `pulseFunction` above and make it periodic. Give it a variable period length (we will eventually make this 40 as shown by the vertical dotted lines above).
def periodicPulseFunction(x, period): """ x : the x values to consider period : the period of the function """ n = x // period x = x - n*period return pulseFunction(x)
_____no_output_____
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Plot your `periodicPulseFunction` with a period of $40$ from $-100$ to $100$ and check that it is correctly
## TO DO: Plot your periodicPulseFunction with a period of 40 from x = -100 to x = 100 x = np.linspace(-100,100,1000) plt.plot(x,periodicPulseFunction(x, 40))
_____no_output_____
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Step 2: Define the Fourier Series This function is neither odd nor even, so we're going to have to take into account both the the even coefficients $a_k$ and the odd coefficients $b_k$. $$ f(x) = \sum\limits_{k=0}^{\infty} a_k cos\left(\frac{2\pi k x}{T}\right) + b_k sin\left(\frac{2\pi k x}{T}\right) $$ Complete th...
def fourierSeriesSum(k, ak, bk, x, period): """ Parameters: k : the maximum k value to include in the summation above ak : an array of length 'k' containing the even coefficients (from a_0 to a_(k-1)) bk : an array of length 'k' containing the odd coefficients (from b_0 to b_(k-1)) ...
_____no_output_____
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Step 3: Define the Integrands Because we have both even and odd terms, we're going to have two separate integrals:The integral to solve for the even terms:$$ a_k = \frac{1}{T} \int\limits_{0}^{T} f(x, \text{period}) \cos\left(\frac{2\pi k x}{T} \right) dx$$The integral to solve for the odd terms:$$ b_k = \frac{1}{T} \...
def odd_integrand(x, f, k, period): """ Parameters: x: the x values to consider f: the function f(x, period) used in the integral k: the k value to use period: the period of f """ integrand = (1/period)*f(x,period)*np.sin(2*np.pi*k*x/period) return integrand def even_...
_____no_output_____
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Step 4: Find the Fourier Coefficients Ok! Now it's time to find the coefficients. This is the same process as last time:1. Initialize an $a_k$ and $b_k$ array2. Loop through all the $k$ values3. Find $a_k[i]$ and $b_k[i]$ where i $\in [0, k]$4. Return $a_k$ and $b_k$(At the end of your quad function, add "limit = 100"...
def findFourierCoefficients(f, k, period): """ Parameters: f: the function to evaluate k: the maximum k value to consider period: the period of f """ ak = np.array([]) for i in range(k+1): temp = quad(even_integrand, 0, period, args=(f,i,period,), limit = 100) ...
_____no_output_____
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Step 5: Putting it all Together Let's test it out!
k = 100 period = 40 [ak, bk] = findFourierCoefficients(periodicPulseFunction, k, period) y = fourierSeriesSum(k, ak, bk, x, period) plt.plot(x, y) plt.title("Pulse Function Constructed from Fourier Series") plt.show()
_____no_output_____
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Step 6: Analyzing the Signal Let's visualize what the coeffcients look like. Plot the even coefficients ($a_k$ versus $k$).
# TO DO: Plot ak versus k k = 100 period = 40 x = np.linspace(0,100,101) plt.plot(x, findFourierCoefficients(periodicPulseFunction, k, period)[0]) # print(findFourierCoefficients(periodicPulseFunction, k, period)[0])
_____no_output_____
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Plot the odd coefficients ($b_k$ versus $k$).
# TO DO: Plot bk versus k k = 100 period = 40 x = np.linspace(0,100,101) plt.plot(x, findFourierCoefficients(periodicPulseFunction, k, period)[1])
_____no_output_____
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Part 2: Application Option 1 Below I've imported and plotted a signal for you. Break down this signal into sines and cosines, and plot the coefficients ($a_k$ versus $k$ and $b_k$ versus $k$)
x, y = np.loadtxt("signal.txt", unpack=True) plt.figure(figsize=(15, 5)) plt.plot(x, y) plt.show() print(len(x)) print(x) period = 15.70796327 def periodicFunction(inp): """ inp : point to find value for """ while inp > period: inp = inp - period for i in range(1000): if (abs(inp - ...
<ipython-input-93-3ee181dc2d3b>:11: IntegrationWarning: The integral is probably divergent, or slowly convergent. temp = quad(even_integrand, 0, period, args=(f,i,period,), limit = 100) <ipython-input-93-3ee181dc2d3b>:11: IntegrationWarning: The maximum number of subdivisions (100) has been achieved. If increasing ...
MIT
FourierTransforms.ipynb
nbasu1/capstone-physics
Computer Vision Nanodegree Project: Image Captioning---The Microsoft **C**ommon **O**bjects in **CO**ntext (MS COCO) dataset is a large-scale dataset for scene understanding. The dataset is commonly used to train and benchmark object detection, segmentation, and captioning algorithms. ![Sample Dog Output](images/coc...
import os import sys sys.path.append('/opt/cocoapi/PythonAPI') from pycocotools.coco import COCO # initialize COCO API for instance annotations dataDir = '/opt/cocoapi' dataType = 'val2014' instances_annFile = os.path.join(dataDir, 'annotations/instances_{}.json'.format(dataType)) coco = COCO(instances_annFile) # ini...
loading annotations into memory... Done (t=6.51s) creating index... index created! loading annotations into memory... Done (t=0.47s) creating index... index created!
MIT
P2_Image_Captioning/.ipynb_checkpoints/0_Dataset-checkpoint.ipynb
arvcode/computer_vision_DNN
Step 2: Plot a Sample ImageNext, we plot a random image from the dataset, along with its five corresponding captions. Each time you run the code cell below, a different image is selected. In the project, you will use this dataset to train your own model to generate captions from images!
import numpy as np import skimage.io as io import matplotlib.pyplot as plt %matplotlib inline # pick a random image and obtain the corresponding URL ann_id = np.random.choice(ids) img_id = coco.anns[ann_id]['image_id'] img = coco.loadImgs(img_id)[0] url = img['coco_url'] # print URL and visualize corresponding image ...
http://images.cocodataset.org/val2014/COCO_val2014_000000524456.jpg
MIT
P2_Image_Captioning/.ipynb_checkpoints/0_Dataset-checkpoint.ipynb
arvcode/computer_vision_DNN
---_You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._--- Assignment 2 - Introduction...
import nltk import pandas as pd import numpy as np nltk.download('punkt') nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') # If you would like to work with the raw text you can use 'moby_raw' with open('moby.txt', 'r') as f: moby_raw = f.read() # If you would like to work with the novel i...
[nltk_data] Downloading package punkt to /home/austin/nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package wordnet to /home/austin/nltk_data... [nltk_data] Package wordnet is already up-to-date! [nltk_data] Downloading package averaged_perceptron_tagger to [nltk_data] /h...
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Example 1How many tokens (words and punctuation symbols) are in text1?*This function should return an integer.*
def example_one(): return len(nltk.word_tokenize(moby_raw)) # or alternatively len(text1)
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Example 2How many unique tokens (unique words and punctuation) does text1 have?*This function should return an integer.*
def example_two(): return len(set(nltk.word_tokenize(moby_raw))) # or alternatively len(set(text1))
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Example 3After lemmatizing the verbs, how many unique tokens does text1 have?*This function should return an integer.*
from nltk.stem import WordNetLemmatizer def example_three(): lemmatizer = WordNetLemmatizer() lemmatized = [lemmatizer.lemmatize(w,'v') for w in text1] return len(set(lemmatized))
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 1What is the lexical diversity of the given text input? (i.e. ratio of unique tokens to the total number of tokens)*This function should return a float.*
from nltk.stem import WordNetLemmatizer def answer_one(): lemmatizer = WordNetLemmatizer() #instantiate WordNetLemmatizer lemmatized = [lemmatizer.lemmatize(w) for w in text1] # use list comprehension to lemmatize each work in text1 total = len(lemmatized) #calculate the total lemmas unique =...
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 2What percentage of tokens is 'whale'or 'Whale'?*This function should return a float.*
from nltk.stem import WordNetLemmatizer def answer_two(): tokens = nltk.word_tokenize(moby_raw) #tokenize moby_raw dist = nltk.FreqDist(tokens) #calculate the distribution of tokens whale_freq = dist.freq("whale") Whale_freq = dist.freq("Whale") #access the frequency distributions for 'whale...
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 3What are the 20 most frequently occurring (unique) tokens in the text? What is their frequency?*This function should return a list of 20 tuples where each tuple is of the form `(token, frequency)`. The list should be sorted in descending order of frequency.*
def answer_three(): tokens = nltk.word_tokenize(moby_raw) #tokenize moby_raw # top_20 = dist.pformat(maxlen=20) # top_20_split = top_20.split(',') # word = [] # count = [] # for i,value in enumerate(top_20_split): # word.append(top_20_split[i].split(':')[0].replace...
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 4What tokens have a length of greater than 5 and frequency of more than 150?*This function should return an alphabetically sorted list of the tokens that match the above constraints. To sort your list, use `sorted()`*
def answer_four(): tokens = nltk.word_tokenize(moby_raw) #tokenize moby_raw dist = nltk.FreqDist(tokens) #calculate the distribution of tokens fivechars_onefiftytimes = [w for w in dist if len(w) > 5 and dist[w] > 150] # use list comprehension to return tokens greater than length 5 that h...
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 5Find the longest word in text1 and that word's length.*This function should return a tuple `(longest_word, length)`.*
def answer_five(): lemmatizer = nltk.WordNetLemmatizer() #instantiate WordNetLemmatizer lemmatized = [lemmatizer.lemmatize(w) for w in text1] #create a list of lemmas using the lemmatizer instance dist = nltk.FreqDist(lemmatized) #calculate the distribution of lemmas # first_answer = ([w ...
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 6What unique words have a frequency of more than 2000? What is their frequency?"Hint: you may want to use `isalpha()` to check if the token is a word and not punctuation."*This function should return a list of tuples of the form `(frequency, word)` sorted in descending order of frequency.*
def answer_six(): tokens = nltk.word_tokenize(moby_raw) #instantiate WordNetLemmatizer dist = nltk.FreqDist(tokens) #calculate the distribution of lemmas token = [w for w in dist if w.isalpha() and dist[w] > 2000] #use list comprehension to return tokens that are words and have a frequency gr...
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 7What is the average number of tokens per sentence?*This function should return a float.*
def answer_seven(): sentences = nltk.sent_tokenize(moby_raw) #instantiate a sentence tokenizer instance text_sentences = nltk.Text(sentences) counter = 0 sum_total = 0 for i,sentence in enumerate(sentences): sum_total += len(nltk.word_tokenize(sentence)) #loop through sentenc...
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 8What are the 5 most frequent parts of speech in this text? What is their frequency?*This function should return a list of tuples of the form `(part_of_speech, frequency)` sorted in descending order of frequency.*
def answer_eight(): tokens = nltk.word_tokenize(moby_raw) #instantiate a sentence tokenizer instance tags = nltk.pos_tag(tokens) #create list of tokens with their respective parts of speech pos_tag = [] for i,tag in enumerate(tags): pos_tag.append(tag[1]) #create a list of all part...
_____no_output_____
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Part 2 - Spelling RecommenderFor this part of the assignment you will create three different spelling recommenders, that each take a list of misspelled words and recommends a correctly spelled word for every word in the list.For every misspelled word, the recommender should find find the word in `correct_spellings` th...
from nltk.corpus import words nltk.download('words') correct_spellings = words.words() # list of correctly spelled words
[nltk_data] Downloading package words to /home/austin/nltk_data... [nltk_data] Package words is already up-to-date!
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 9For this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:**[Jaccard distance](https://en.wikipedia.org/wiki/Jaccard_index) on the trigrams of the two words.***This function should return a list of length three:`['cormule...
def answer_nine(entries=['cormulent', 'incendenece', 'validrate']): entries = entries jaccard_list = [] for i in range(len(entries)): jaccard_dict = {} for j,word in enumerate(correct_spellings): jaccard_dict[word] = nltk.jaccard_distance(set(nltk.ngrams(word,n=3)), ...
corpulent: 0.60 indecence: 0.67 validate: 0.56
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 10For this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:**[Jaccard distance](https://en.wikipedia.org/wiki/Jaccard_index) on the 4-grams of the two words.***This function should return a list of length three:`['cormule...
def answer_ten(entries=['cormulent', 'incendenece', 'validrate']): #same as above, but for 4-grams instead of 3-grams entries = entries jaccard_list = [] for i in range(len(entries)): jaccard_dict = {} for j,word in enumerate(correct_spellings): jaccard_dict[word...
cormus: 0.71 incendiary: 0.75 valid: 0.67
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Question 11For this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:**[Edit distance on the two words with transpositions.](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)***This function should return a list o...
def answer_eleven(entries=['cormulent', 'incendenece', 'validrate']): #use edit distance instead of Jaccard distance to recommend correct spelling edit_list = [] for i in range(len(entries)): edit_dict = {} for j,word in enumerate(correct_spellings): edit_dict[word] = nltk.e...
corpulent: 1.0 intendence: 2.0 validate: 1.0
MIT
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
Documentation> 201025: This notebook generate embedding vectors for pfam_motors, df_dev, and motor_toolkit from the models that currently finished training: - lstm5 - evotune_lstm_5_balanced.pt - evotune_lstm_5_balanced_target.pt - mini_lstm_5_balanced.pt - mini_lstm_5_b...
import math import torch.nn as nn import argparse import random import warnings import numpy as np import torch import torch.nn.functional as F from torch import optim import torch.backends.cudnn as cudnn from torch.utils.data import DataLoader from torch.utils.data import Dataset from torch.autograd import Variable im...
loaded dict file for weights ../../data/201025/evotune_transformer_encoder_mlm_balanced_target.pt output embedding for pfamA_motors_balanced At Epoch: 0.00 HQDNVHARSLMGLVRNVFEQAGLEKTALDAVAVSSGPGSYTGLRIGVSVAKGLAYALDKPVIGVGTLEALAFRAIPFSDSTDTIIPMLDARRMEVYALVMDGLGDTLISPQPFILEDNPFMEYLEKGKVFFLGDGVPKSKEILSHPNSRFVPLFNSSQSIGELA...
MIT
code/evo_tune_201023/generate_embedding_transformer.ipynb
steveyu323/motor_embedding
7-3. HHLアルゴリズムを用いたポートフォリオ最適化この節では論文[1]を参考に、過去の株価変動のデータから、最適なポートフォリオ(資産配分)を計算してみよう。ポートフォリオ最適化は、[7-1節](7.1_quantum_phase_estimation_detailed.ipynb)で学んだHHLアルゴリズムを用いることで、従来より高速に解けることが期待されている問題の一つである。今回は具体的に、GAFA (Google, Apple, Facebook, Amazon) の4社の株式に投資する際、どのような資産配分を行えば最も低いリスクで高いリターンを得られるかという問題を考える。 株価データ取得まずは各社の株価データを...
# データ取得に必要なpandas, pandas_datareaderのインストール # !pip install pandas pandas_datareader import numpy as np import pandas as pd import pandas_datareader.data as web import datetime import matplotlib.pyplot as plt # 銘柄選択 codes = ['GOOG', 'AAPL', 'FB', 'AMZN'] # GAFA # 2017年の1年間のデータを使用 start = datetime.datetime(2017, 1, 1) e...
_____no_output_____
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
※ここで、4つの銘柄を2つのグループに分けているのは、株価の値がそれぞれ近くプロット時に見やすいからであり、深い意味はない。 データの前処理次に、取得した株価を日次リターンに変換し、いくつかの統計量を求めておく。 日次リターンへの変換個別銘柄の日次リターン(変化率) $y_t$ ($t$は日付)は以下で定義される。 $$y_t = \frac{P_t - P_{t-1}}{P_{t-1}}$$これは `pandas DataFrame` の `pct_change()` メソッドで得られる。
daily_return = df.pct_change() display(daily_return.tail())
_____no_output_____
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
期待リターン銘柄ごとの期待リターン$\vec R$を求める。ここでは過去のリターンの算術平均を用いる:$$\vec R = \frac{1}{T} \sum_{t= 1}^{T} \vec y_t$$
expected_return = daily_return.dropna(how='all').mean() * 252 # 年率換算のため年間の営業日数252を掛ける print(expected_return)
Symbols GOOG 0.300215 AAPL 0.411192 FB 0.430156 AMZN 0.464567 dtype: float64
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
分散・共分散行列リターンの標本不偏分散・共分散行列$\Sigma$は以下で定義される。$$\Sigma = \frac{1}{T-1} \sum_{t=1}^{T} ( \vec y_t -\vec R ) (\vec y_t -\vec R )^T$$
cov = daily_return.dropna(how='all').cov() * 252 # 年率換算のため display(cov)
_____no_output_____
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
ポートフォリオ最適化準備が整ったところで、ポートフォリオ最適化に取り組もう。まず、ポートフォリオ(i.e., 資産配分)を4成分のベクトル $\vec{w} = (w_0,w_1,w_2,w_3)^T$ で表す。これは各銘柄を持つ割合(ウェイト)を表しており、例えば $\vec{w}=(1,0,0,0)$ であれば Google 株に全資産の100%を投入しするポートフォリオを意味する。以下の式を満たすようなポートフォリオを考えてみよう。$$\min_{\vec{w}} \frac{1}{2} \vec{w}^T \Sigma \vec{w} \:\:\: \text{s.t.} \:\: \vec R^T \vec w = \m...
R = expected_return.values Pi = np.ones(4) S = cov.values row1 = np.append(np.zeros(2), R).reshape(1,-1) row2 = np.append(np.zeros(2), Pi).reshape(1,-1) row3 = np.concatenate([R.reshape(-1,1), Pi.reshape(-1,1), S], axis=1) W = np.concatenate([row1, row2, row3]) np.set_printoptions(linewidth=200) print(W) ## Wの固有値を確認 ...
[-2.11207187 -0.10947986 0.01121933 0.01864265 0.11919724 2.20027702]
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
右辺ベクトルの作成以下でポートフォリオの期待リターン $\mu$ を指定すると、そのようなリターンをもたらす最もリスクの小さいポートフォリオを計算できる。$\mu$ は自由に設定できる。一般に期待リターンが大きいほどリスクも大きくなるが、ここでは例として10%としておく(GAFA株がガンガン上がっている時期なので、これはかなり弱気な方である)。
mu = 0.1 # ポートフォリオのリターン(手で入れるパラメータ) xi = 1.0 mu_xi_0 = np.append(np.array([mu, xi]), np.zeros_like(R)) ## (1)式の右辺のベクトル print(mu_xi_0)
[0.1 1. 0. 0. 0. 0. ]
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
量子系で扱えるように行列を拡張する$W$ は6次元なので、3量子ビットあれば量子系で計算可能である ($2^3 = 8$)。そこで、拡張した2次元分を0で埋めた行列とベクトルも作っておく。
nbit = 3 ## 状態に使うビット数 N = 2**nbit W_enl = np.zeros((N, N)) ## enl は enlarged の略 W_enl[:W.shape[0], :W.shape[1]] = W.copy() mu_xi_0_enl = np.zeros(N) mu_xi_0_enl[:len(mu_xi_0)] = mu_xi_0.copy()
_____no_output_____
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
以上で、連立方程式(1)を解く準備が整った。 HHLアルゴリズムを用いた最小分散ポートフォリオ算出それでは、HHL アルゴリズムを用いて、連立一次方程式(1)を解いていこう。先ずはその下準備として、* 古典データ $\mathbf{x}$ に応じて、量子状態を $|0\cdots0\rangle \to \sum_i x_i |i \rangle$ と変換する量子回路を返す関数 `input_state_gate` (本来は qRAM の考え方を利用して作るべきだが、シミュレータを使っているので今回は non-unitary なゲートとして実装してしまう。また、規格化は無視している)* 制御位相ゲートを返す関数 `CPhaseGat...
# Qulacs のインストール # !pip install qulacs ## Google Colaboratory / (Linux or Mac)のjupyter notebook 環境の場合にのみ実行してください。 ## Qulacsのエラーが正常に出力されるようになります。 !pip3 install wurlitzer %load_ext wurlitzer import numpy as np from qulacs import QuantumCircuit, QuantumState, gate from qulacs.gate import merge, Identity, H, SWAP def inp...
_____no_output_____
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
まずはHHLアルゴリズムに必要なパラメータを設定する。クロックレジスタ量子ビット数 `reg_nbit`を `7` とし、行列 $W$ のスケーリングに使う係数 `scale_fac` を`1` とする(つまり、スケールさせない)。また、制御回転ゲートに使う係数 $c$ は、`reg_nbit` ビットで表せる非ゼロの最も小さい数の半分にとっておく。
# 位相推定に使うレジスタの数 reg_nbit = 7 ## W_enl をスケールする係数 scale_fac = 1. W_enl_scaled = scale_fac * W_enl ## W_enl_scaledの固有値として想定する最小の値 ## 今回は射影が100%成功するので, レジスタで表せる最小値の定数倍でとっておく C = 0.5*(2 * np.pi * (1. / 2**(reg_nbit) ))
_____no_output_____
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
HHLアルゴリズムの核心部分を書いていく。今回は、シミュレータ qulacs を使うので様々な簡略化を行なっている。HHLアルゴリズムがどのように動作するのかについての感覚を知る実装と思っていただきたい。* 入力状態 $|\mathbf{b}\rangle$ を用意する部分は簡略化* 量子位相推定アルゴリズムで使う $e^{iA}$ の部分は、 $A$ を古典計算機で対角化したものを使う* 逆数をとる制御回転ゲートも、古典的に行列を用意して実装* 補助ビット $|0 \rangle{}_{S}$ への射影測定を行い、測定結果 `0` が得られた状態のみを扱う(実装の都合上、制御回転ゲートの作用の定義を[7-1節](7.1_quant...
from functools import reduce ## 対角化. AP = PD <-> A = P*D*P^dag D, P = np.linalg.eigh(W_enl_scaled) ##################################### ### HHL量子回路を作る. 0番目のビットから順に、Aの作用する空間のbit達 (0番目 ~ nbit-1番目), ### register bit達 (nbit番目 ~ nbit+reg_nbit-1番目), conditional回転用のbit (nbit+reg_nbit番目) ### とする. #########################...
_____no_output_____
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
HHL アルゴリズムによる解 `x_HHL` と、通常の古典計算の対角化による解 `x_exact` を比べると、概ね一致していることが分かる。(HHLアルゴリズムの精度を決めるパラメータはいくつかある(例えば`reg_nbit`)ので、それらを変えて色々試してみて頂きたい。)
## 厳密解 x_exact = np.linalg.lstsq(W_enl, mu_xi_0_enl, rcond=0)[0] print("HHL: ", x_HHL) print("exact:", x_exact) rel_error = np.linalg.norm(x_HHL- x_exact) / np.linalg.norm(x_exact) print("rel_error", rel_error)
HHL: [ 0.09580738 -0.04980738 2.36660125 0.09900883 -0.47774813 -0.98438791 0. 0. ] exact: [ 0.15426894 -0.07338059 2.29996915 0.17711988 -0.66526695 -0.81182208 0. 0. ] rel_error 0.11097291393510306
BSD-3-Clause
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo