markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Choose the model with the highest topic coherence.
model, tc = max(model_list, key=lambda x: x[1]) print('Topic coherence: %.3e' %tc)
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
We save the model, to avoid having to train it again, and also show how to load it again.
# Save model. model.save('/tmp/model.atmodel') # Load model. model = AuthorTopicModel.load('/tmp/model.atmodel')
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Explore author-topic representation Now that we have trained a model, we can start exploring the authors and the topics. First, let's simply print the most important words in the topics. Below we have printed topic 0. As we can see, each topic is associated with a set of words, and each word has a probability of being ...
model.show_topic(0)
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Below, we have given each topic a label based on what each topic seems to be about intuitively.
topic_labels = ['Circuits', 'Neuroscience', 'Numerical optimization', 'Object recognition', \ 'Math/general', 'Robotics', 'Character recognition', \ 'Reinforcement learning', 'Speech recognition', 'Bayesian modelling']
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Rather than just calling model.show_topics(num_topics=10), we format the output a bit so it is easier to get an overview.
for topic in model.show_topics(num_topics=10): print('Label: ' + topic_labels[topic[0]]) words = '' for word, prob in model.show_topic(topic[0]): words += word + ' ' print('Words: ' + words) print()
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
These topics are by no means perfect. They have problems such as chained topics, intruded words, random topics, and unbalanced topics (see Mimno and co-authors 2011). They will do for the purposes of this tutorial, however. Below, we use the model[name] syntax to retrieve the topic distribution for an author. Each topi...
model['YannLeCun']
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Let's print the top topics of some authors. First, we make a function to help us do this more easily.
from pprint import pprint def show_author(name): print('\n%s' % name) print('Docs:', model.author2doc[name]) print('Topics:') pprint([(topic_labels[topic[0]], topic[1]) for topic in model[name]])
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Below, we print some high profile researchers and inspect them. Three of these, Yann LeCun, Geoffrey E. Hinton and Christof Koch, are spot on. Terrence J. Sejnowski's results are surprising, however. He is a neuroscientist, so we would expect him to get the "neuroscience" label. This may indicate that Sejnowski works ...
show_author('YannLeCun') show_author('GeoffreyE.Hinton') show_author('TerrenceJ.Sejnowski') show_author('ChristofKoch')
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Simple model evaluation methods We can compute the per-word bound, which is a measure of the model's predictive performance (you could also say that it is the reconstruction error). To do that, we need the doc2author dictionary, which we can build automatically.
from gensim.models import atmodel doc2author = atmodel.construct_doc2author(model.corpus, model.author2doc)
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Now let's evaluate the per-word bound.
# Compute the per-word bound. # Number of words in corpus. corpus_words = sum(cnt for document in model.corpus for _, cnt in document) # Compute bound and divide by number of words. perwordbound = model.bound(model.corpus, author2doc=model.author2doc, \ doc2author=model.doc2author) / corpus_...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
We can evaluate the quality of the topics by computing the topic coherence, as in the LDA class. Use this to e.g. find out which of the topics are poor quality, or as a metric for model selection.
%time top_topics = model.top_topics(model.corpus)
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Plotting the authors Now we're going to produce the kind of pacific archipelago looking plot below. The goal of this plot is to give you a way to explore the author-topic representation in an intuitive manner. We take all the author-topic distributions (stored in model.state.gamma) and embed them in a 2D space. To do t...
%%time from sklearn.manifold import TSNE tsne = TSNE(n_components=2, random_state=0) smallest_author = 0 # Ignore authors with documents less than this. authors = [model.author2id[a] for a in model.author2id.keys() if len(model.author2doc[a]) >= smallest_author] _ = tsne.fit_transform(model.state.gamma[authors, :]) #...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
We are now ready to make the plot. Note that if you run this notebook yourself, you will see a different graph. The random initialization of the model will be different, and the result will thus be different to some degree. You may find an entirely different representation of the data, or it may show the same interpret...
# Tell Bokeh to display plots inside the notebook. from bokeh.io import output_notebook output_notebook() from bokeh.models import HoverTool from bokeh.plotting import figure, show, ColumnDataSource x = tsne.embedding_[:, 0] y = tsne.embedding_[:, 1] author_names = [model.id2author[a] for a in authors] # Radius of e...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
The circles in the plot above are individual authors, and their sizes represent the number of documents attributed to the corresponding author. Hovering your mouse over the circles will tell you the name of the authors and their sizes. Large clusters of authors tend to reflect some overlap in interest. We see that the...
from gensim.similarities import MatrixSimilarity # Generate a similarity object for the transformed corpus. index = MatrixSimilarity(model[list(model.id2author.values())]) # Get similarities to some author. author_name = 'YannLeCun' sims = index[model[author_name]]
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
However, this framework uses the cosine distance, but we want to use the Hellinger distance. The Hellinger distance is a natural way of measuring the distance (i.e. dis-similarity) between two probability distributions. Its discrete version is defined as $$ H(p, q) = \frac{1}{\sqrt{2}} \sqrt{\sum_{i=1}^K (\sqrt{p_i} - ...
# Make a function that returns similarities based on the Hellinger distance. from gensim import matutils import pandas as pd # Make a list of all the author-topic distributions. author_vecs = [model.get_author_topics(author) for author in model.id2author.values()] def similarity(vec1, vec2): '''Get similarity be...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Now we can find the most similar authors to some particular author. We use the Pandas library to print the results in a nice looking tables.
get_table('YannLeCun')
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
As before, we can specify the minimum author size.
get_table('JamesM.Bower', smallest_author=3)
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Serialized corpora The AuthorTopicModel class accepts serialized corpora, that is, corpora that are stored on the hard-drive rather than in memory. This is usually done when the corpus is too big to fit in memory. There are, however, some caveats to this functionality, which we will discuss here. As these caveats make ...
%time model_ser = AuthorTopicModel(corpus=corpus, num_topics=10, id2word=dictionary.id2token, \ author2doc=author2doc, random_state=1, serialized=True, \ serialization_path='/tmp/model_serialization.mm') # Delete the file, once you're done using it. import ...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Feed sequences to the TM
# create sequences allSequences = [] for s in range(numSequences): if s % 2 == 0: sequence = generateRandomSequence(symbolsPerSequence, tm.numberOfColumns(), sparsity) allSequences.append(sequence) else: sequenceHO = generateHOSequence(sequence, symbolsPerSequence, tm.numberOfCo...
projects/neural_correlations/EXP2-HighOrder/NeuCorr_Exp2.ipynb
subutai/htmresearch
agpl-3.0
ISI analysis (with Poisson model too)
subSpikeTrains = subSample(spikeTrains, 1000, tm.numberOfCells(), 0, 0) isi = computeISI(subSpikeTrains) # Print ISI distribution of TM #bins = np.linspace(np.min(isi), np.max(isi), 50) bins = 100 plt.hist(isi, bins) plt.xlim(0,1000) # plt.xlim(89500,92000) plt.xlabel("ISI") plt.ylabel("Frequency") plt.savefig("isiT...
projects/neural_correlations/EXP2-HighOrder/NeuCorr_Exp2.ipynb
subutai/htmresearch
agpl-3.0
Raster Plots
subSpikeTrains = subSample(spikeTrains, 100, tm.numberOfCells(), -1, 1000) rasterPlot(subSpikeTrains, "TM") pSpikeTrain = poissonSpikeGenerator(firingRate,np.shape(subSpikeTrains)[1],np.shape(subSpikeTrains)[0]) rasterPlot(pSpikeTrain, "Poisson")
projects/neural_correlations/EXP2-HighOrder/NeuCorr_Exp2.ipynb
subutai/htmresearch
agpl-3.0
Quick Accuracy Test
simpleAccuracyTest("random", tm, allSequences)
projects/neural_correlations/EXP2-HighOrder/NeuCorr_Exp2.ipynb
subutai/htmresearch
agpl-3.0
Elad Plot
# Sample from both TM_SpikeTrains and Poisson_SpikeTrains. 10 cells for 1000 (?) timesteps wordLength = 10 firingRate = np.mean(subSpikeTrains) * 1000 # generate all 2^N strings: binaryStrings = list(itertools.product([0, 1], repeat=wordLength)) trials = 10 x = [] #observed y = [] #predicted by random model for t ...
projects/neural_correlations/EXP2-HighOrder/NeuCorr_Exp2.ipynb
subutai/htmresearch
agpl-3.0
Save TM
saveTM(tm) # to load the TM back from the file do: with open('tm.nta', 'rb') as f: proto2 = TemporalMemoryProto_capnp.TemporalMemoryProto.read(f, traversal_limit_in_words=2**61) tm = TM.read(proto2)
projects/neural_correlations/EXP2-HighOrder/NeuCorr_Exp2.ipynb
subutai/htmresearch
agpl-3.0
Analysis of input
overlapMatrix = inputAnalysis(allSequences, "random", tm.numberOfColumns()) # show heatmap of overlap matrix plt.imshow(overlapMatrix, cmap='spectral', interpolation='nearest') cb = plt.colorbar() cb.set_label('Overlap Score') plt.savefig("overlapScore_heatmap") plt.close() # plt.show() # generate histogram bins = 60...
projects/neural_correlations/EXP2-HighOrder/NeuCorr_Exp2.ipynb
subutai/htmresearch
agpl-3.0
1. First lets make some fake data
#a handful of sites sites = ['org','A','B','C','D','E','F','G','H','I','J','K'] #non symetric distances distances = dict( ((a,b),np.random.randint(10,50)) for a in sites for b in sites if a!=b )
05-routes-and-schedules/traveling_salesman.ipynb
cochoa0x1/integer-programming-with-python
mit
The model We are going to model this problem as an integer program. Lets imagine we have a tour through our sites, and site i is in the tour followed by site j. We can model this with a binary variable $x_{i,j}$ that should be 1 only when site i is connected to site j. $$x_{i,j} = \begin{cases} 1, & \text{if site i...
#create the problme prob=LpProblem("salesman",LpMinimize) #indicator variable if site i is connected to site j in the tour x = LpVariable.dicts('x',distances, 0,1,LpBinary) #the objective cost = lpSum([x[(i,j)]*distances[(i,j)] for (i,j) in distances]) prob+=cost #constraints for k in sites: #every site has exac...
05-routes-and-schedules/traveling_salesman.ipynb
cochoa0x1/integer-programming-with-python
mit
Subtours and why we need way more constraints There is still something missing in our solution. Lets imagine we have 6 sites A,B,C,D,E,F. Does the following satisfy our existing constraints? $$A->B->C->A \ and \ D->E->F->D$$ Each site is visited only once and has only one inbound and one outbound connection, so yes, it...
#we need to keep track of the order in the tour to eliminate the possibility of subtours u = LpVariable.dicts('u', sites, 0, len(sites)-1, LpInteger) #subtour elimination N=len(sites) for i in sites: for j in sites: if i != j and (i != 'org' and j!= 'org') and (i,j) in x: prob += u[i] - u[j] <=...
05-routes-and-schedules/traveling_salesman.ipynb
cochoa0x1/integer-programming-with-python
mit
And the result:
sites_left = sites.copy() org = 'org' tour=[] tour.append(sites_left.pop( sites_left.index(org))) while len(sites_left) > 0: for k in sites_left: if x[(org,k)].varValue ==1: tour.append( sites_left.pop( sites_left.index(k))) org=k break tour.append('org...
05-routes-and-schedules/traveling_salesman.ipynb
cochoa0x1/integer-programming-with-python
mit
The total tour length:
sum(tour_legs)
05-routes-and-schedules/traveling_salesman.ipynb
cochoa0x1/integer-programming-with-python
mit
Attribute Information: No: row number year: year of data in this row month: month of data in this row day: day of data in this row hour: hour of data in this row pm2.5: PM2.5 concentration (ug/m^3) DEWP: Dew Point (ƒ) TEMP: Temperature (ƒ) PRES: Pressure (hPa) cbwd: Combined wind direction Iws: Cumulated win...
pm2 = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/00381/PRSA_data_2010.1.1-2014.12.31.csv', na_values='NA') pm2.columns = ['id', 'year', 'month', 'day', 'hour', 'pm2', 'dew_point', 'temperature', 'pressure', 'wind_dir', 'wind_speed', 'hours_snow', 'hours_rain']...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
There ore over 2000 samples with the pm 2.5 value missing: since this is the value to predict I am going to drop them.
pm2.dropna(inplace=True) pm2.describe().T pm2.describe(include=['O']) pm2.wind_dir.value_counts()
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
2 - Suppose our data became corrupted after we downloaded it and values were missing. Randomly insert 5000 NaN into the dataset accross all the columns.
# setting the seed np.random.seed(0) # creating an array of dimension equal to the number of cells of the dataframe and with exactly 5000 ones dim = pm2.shape[0]*pm2.shape[1] arr = np.array([0]*(dim-5000) + [1]*5000) # shuffling and reshaping the array np.random.shuffle(arr) arr = arr.reshape(pm2.shape[0], pm2.shape[1]...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
3 - Which variables lend themselves to be in a regression model? Select those variables, and then fit a regression model for each of the following imputation strategies, commenting on your results. - Dropping all rows with at least 1 NA - Dropping all rows with at least 3 NA - Imputing 0 - Mean - M...
# I'm dropping wind_dir and id regr_cols = ['year', 'month', 'day', 'hour', 'dew_point', 'temperature', 'pressure', 'wind_speed', 'hours_snow', 'hours_rain', 'pm2'] pm2_regr = pm2.loc[:, regr_cols] # in the solution there is no year, month, day and hour # also, he discards hours_snow and hours_rain (though...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Dropping all rows with at least 1 NA:
lr.fit(pm2_regr.dropna().iloc[:, :-1], pm2_regr.dropna().iloc[:, -1]) lr.score(pm2_regr.dropna().iloc[:, :-1], pm2_regr.dropna().iloc[:, -1])
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Dropping all row with at least 3 NA gets me an error because I have nans in some rows:
lr.fit(pm2_regr.dropna(thresh=5).iloc[:, :-1], pm2_regr.dropna(thresh=5).iloc[:, -1]) lr.score(pm2_regr.dropna(thresh=5).iloc[:, :-1], pm2_regr.dropna(thresh=5).iloc[:, -1])
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Imputing 0:
lr.fit(pm2_regr.fillna(0).iloc[:, :-1], pm2_regr.fillna(0).iloc[:, -1]) lr.score(pm2_regr.fillna(0).iloc[:, :-1], pm2_regr.fillna(0).iloc[:, -1])
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Imputing the mean:
imp = Imputer(strategy='mean') pm2_regr_mean = imp.fit_transform(pm2_regr) lr.fit(pm2_regr_mean[:, :-1], pm2_regr_mean[:, -1]) lr.score(pm2_regr_mean[:, :-1], pm2_regr_mean[:, -1])
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
The median:
imp = Imputer(strategy='median') pm2_regr_median = imp.fit_transform(pm2_regr) lr.fit(pm2_regr_median[:, :-1], pm2_regr_median[:, -1]) lr.score(pm2_regr_median[:, :-1], pm2_regr_median[:, -1])
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
And the mode:
imp = Imputer(strategy='most_frequent') pm2_regr_mode = imp.fit_transform(pm2_regr) lr.fit(pm2_regr_mode[:, :-1], pm2_regr_mode[:, -1]) lr.score(pm2_regr_mode[:, :-1], pm2_regr_mode[:, -1])
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
The best result I get is from simply dropping all rows with NAs, mean and median gives similar performances while the mode is the worst imputation (surprisingly worst than imputing 0, which is quite random). Overall all strategies doesn't yield good results, I guess this fit is bad in general. 4 - Given the results in ...
pm2_regr_imp = pm2_regr.dropna(subset=['year', 'month', 'day', 'hour', 'pm2']) imp = Imputer(strategy = 'median') pm2_regr_imp = imp.fit_transform(pm2_regr_imp) lr.fit(pm2_regr_imp[:, :-1], pm2_regr_imp[:, -1]) lr.score(pm2_regr_imp[:, :-1], pm2_regr_imp[:, -1])
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
The result is slightly better than simply imputing mean or median, but still worse than dropping all NAs. Categorical Data Sometimes your data will contain categorical variables which need to be handled carefully depending on the machine learning algorithm you choose to use. Encoding categorical variables comes in two...
pm2.describe(include=['O'])
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
The variable is nominal, so I'm going to use one-hot encoding:
# for simplicity I'm using pandas function pm2_enc = pd.get_dummies(pm2) pm2_enc = pm2_enc.loc[:, regr_cols[:-1] + ['wind_dir_NE', 'wind_dir_NW', 'wind_dir_SE', 'wind_dir_cv'] + regr_cols[-1:]].dropna() # from solutions using sklearn: from sklearn.preprocessing import LabelEncoder, OneHotEncoder l_enc = LabelEncoder...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
2 - Perform a multilinear regression, using the classified data, removing the NA values. Comment on your results.
lr.fit(pm2_enc.iloc[:, :-1], pm2_enc.iloc[:, -1]) lr.score(pm2_enc.iloc[:, :-1], pm2_enc.iloc[:, -1])
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
The results are a bit better than before, but the performances are still very bad. 3 - Create a new encoding for days in which it rained, snowed, neither, and both, and then rerun the regression. Are the results any better?
# hours_snow and hours_rain are cumulative across days, so I'm taking the max for each day to see if it snowed days = pm2_enc.groupby(['year', 'month', 'day'])['hours_snow', 'hours_rain'].max() # creating columns for the encodings days['snow'] = pd.Series(days['hours_snow'] > 0, dtype='int') days['rain'] = pd.Series(da...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Wow, now the fit is perfect! 4 - Create a new encoding for the quartile that a day falls under by wind speed and rerun the regression. Comment on your results.
# using pandas cut and subtracting 0.1 to include the min values pm2_enc['wind_speed_quartile'] = pd.cut(pm2_enc.wind_speed, bins=list(pm2_enc.wind_speed.quantile([0])-0.1) + list(pm2_enc.wind_speed.quantile([0.25, 0.5, 0.75, 1])), labels=[...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
The accuracy has gone down again after adding this new column, this may be due to the fact that this adds useless noise to the data or that this binning is too coarse maybe. 5 - Create a new encoding for deciles of the DEWP variable. Then select the row containing the highest temperature, and using Pandas category dat...
# using pandas cut and subtracting 0.1 to include the min values pm2_enc['dew_point_decile'] = pd.cut(pm2_enc.dew_point, bins=list(pm2_enc.dew_point.quantile([0])-0.1) + list(pm2_enc.dew_point.quantile([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]))) # from solutions: not usi...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Feature Scaling Many of the machine learning algorithms we have at our disposal require that the feautures be on the the same scale in order to work properly. In this exercise, you'll test out a few techniques with and without feature scaling and observe the outcomes. 1 - Head over to the Machine Learning Repository, ...
wine = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None) wine.columns = ['class', 'alcohol', 'malic_acid', 'ash', 'alcalinity_ash', 'magnesium', 'total_phenols', 'flavanoids', 'nonflavanoid_phenols', 'proanthocyanins', 'color_intensity', ...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
2 - Fit a Nearest Neighbors model to the data, using a normalized data set, a stardardized data set, and the original. Split into test and train sets and compute the accuracy of the classifications and comment on your results.
from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.model_selection import train_test_split
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Original dataset:
Xtrain, Xtest, ytrain, ytest = train_test_split(wine.iloc[:, 1:], wine.iloc[:, 0], test_size=0.3, random_state=0) knn = KNeighborsClassifier() knn.fit(Xtrain, ytrain) print(knn.score(Xtrain, ytrain)) print(knn.score(Xtest, ytest))
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Normalized dataset:
mms = MinMaxScaler() Xtrain_norm = mms.fit_transform(Xtrain) Xtest_norm = mms.transform(Xtest) knn.fit(Xtrain_norm, ytrain) print(knn.score(Xtrain_norm, ytrain)) print(knn.score(Xtest_norm, ytest))
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Standardized dataset:
ssc = StandardScaler() Xtrain_std = ssc.fit_transform(Xtrain) Xtest_std = ssc.transform(Xtest) knn.fit(Xtrain_std, ytrain) print(knn.score(Xtrain_std, ytrain)) print(knn.score(Xtest_std, ytest))
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
The accuracy is way better for a normalized or standardized dataset, with the least having a slightly better generalization: K-Nearest Neighbors is sensitive to feature scaling. 3 - Fit a Naive Bayes model to the data, using a normalized data set, a standardized data set, and the original. Comment on your results.
from sklearn.naive_bayes import GaussianNB
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Original dataset:
gnb = GaussianNB() gnb.fit(Xtrain, ytrain) print(gnb.score(Xtrain, ytrain)) print(gnb.score(Xtest, ytest))
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Normalized dataset:
gnb.fit(Xtrain_norm, ytrain) print(gnb.score(Xtrain_norm, ytrain)) print(gnb.score(Xtest_norm, ytest))
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Standardized dataset:
gnb.fit(Xtrain_std, ytrain) print(gnb.score(Xtrain_std, ytrain)) print(gnb.score(Xtest_std, ytest))
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
For this algorithm there is no difference at all, so scaling the data isn't necessary. Feature Selection With many datasets, you will find yourself in a situation where not all of the provided features are relevant to your model and it may be best to discard them. This is a very complex topic, involving many technique...
from sklearn.datasets import load_boston boston = load_boston() boston_df = pd.DataFrame(boston.data, columns=boston.feature_names) boston_target = boston.target from sklearn.model_selection import train_test_split Xtrain, Xtest, ytrain, ytest = train_test_split(boston_df, boston_target, test_size=0.3, random_state=...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
2 - Fit a series of least squares multilinear regression models to the data, and use the F-Statistic to select the K best features for values of k ranging from 1 to the total number of features. Plot the MSE for each model against the test set and print the best features for each iteration. Comment on your results.
from sklearn.feature_selection import f_classif, SelectKBest from sklearn.metrics import mean_squared_error # in the solutions he uses f_regression and not f_classif # also, best features are obtained by cols[sel.get_support()] with cols = Xtrain.columns # and lr is instantiated with normalize=True from sklearn.featu...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
The MSE keeps going down adding features, there is a great gain after the 11th feature is added. 3 - Do the same as in part (2) instead this time using recursive feature selection.
from sklearn.feature_selection import RFE mse = [] # looping through the number of features desired and storing the results in mse for k in range(1, boston_df.shape[1]+1): # using Recursive Feature Selection with linear regression as estimator sel = RFE(estimator=lr, n_features_to_select=k) # fitting the s...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
The MSE keeps going down adding features but after the sixth feature is added there isn't much improvement. 4 - Fit a Ridge Regression model to the data and use recursive feature elimination and SelectFromModel in sklearn to select your features. Generate the same plots and best features as in parts (2) and (3) and co...
# in solutions he doesn't use select from model but repeats the previous exercise only using ridge instead # ok no, it does both # in selectfrommodel it uses c_vals = np.arange(0.1, 2.1, 0.1) to loop through and the threshold is set to # str(c) + '*mean' for c in c_vals # also, he always fits the ridge model from skl...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
After the fourth feature there is no improvement. Also, the MSE seems better than all the trials before. 5 - L1 regularization can also be used for model selection. Choose an algorithm in sklearn and repeat part (4) using model selection via regularization.
# again, in solutions he uses the c_vals as before and he fits the lasso from sklearn.linear_model import LassoCV from sklearn.feature_selection import SelectFromModel # fitting ridge regression lasso = LassoCV() c_vals = np.arange(0.1, 2.1, 0.1) cols = Xtrain.columns mse = [] # looping through the possible threshhol...
Data Preprocessing/Preprocessing_exercise.ipynb
aleph314/K2
gpl-3.0
Load training data
df = pd.read_csv('../facies_vectors.csv')
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Build features In the real world it would be unusual to have neutron-density cross-plot porosity (i.e. PHIND) without the corresponding raw input curves, namely bulk density and neutron porosity, as we have in this contest dataset. So as part of the feature engineering process, I back-calculate estimates of those raw c...
def estimate_dphi(df): return ((4*(df['PHIND']**2) - (df['DeltaPHI']**2))**0.5 - df['DeltaPHI']) / 2 def estimate_rhob(df): return (2.71 - (df['DPHI_EST']/100) * 1.71) def estimate_nphi(df): return df['DPHI_EST'] + df['DeltaPHI'] def compute_rhomaa(df): return (df['RHOB_EST'] - (df['PHIND'] / 100)) /...
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Because solving the sum of squares equation involved the quadratic formula, in some cases imaginary numbers result due to porosities being negative, which is what the warning below is about.
df['DPHI_EST'] = df.apply(lambda x: estimate_dphi(x), axis=1).astype(float) df['RHOB_EST'] = df.apply(lambda x: estimate_rhob(x), axis=1) df['NPHI_EST'] = df.apply(lambda x: estimate_nphi(x), axis=1) df['RHOMAA_EST'] = df.apply(lambda x: compute_rhomaa(x), axis=1)
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Regress missing PE values
pe = df.dropna() PE = pe['PE'].values wells = pe['Well Name'].values drop_list_pe = ['Formation', 'Well Name', 'Facies', 'Depth', 'PE', 'RELPOS'] fv_pe = pe.drop(drop_list_pe, axis=1).values X_pe = preprocessing.StandardScaler().fit(fv_pe).transform(fv_pe) y_pe = PE reg = neighbors.KNeighborsRegressor(n_neighbors...
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Apply regression model to missing PE values and merge back into dataframe:
reg.fit(X_pe, y_pe) fv_apply = df.drop(drop_list_pe, axis=1).values X_apply = preprocessing.StandardScaler().fit(fv_apply).transform(fv_apply) df['PE_EST'] = reg.predict(X_apply) df.PE = df.PE.combine_first(df.PE_EST)
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Compute UMAA for lithology model
df['UMAA_EST'] = df.apply(lambda x: compute_umaa(x), axis=1)
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Umaa Rhomaa plot Just for fun, below is a basic Umaa-Rhomaa plot to view relative abundances of quartz, calcite, dolomite, and clay. The red triangle represents a ternary solution for QTZ, CAL, and DOL, while the green triangle represents a solution for QTZ, CAL, and CLAY (illite).
df[df.GR < 125].plot(kind='scatter', x='UMAA_EST', y='RHOMAA_EST', c='GR', figsize=(8,6)) plt.ylim(3.1, 2.2) plt.xlim(0.0, 17.0) plt.plot([4.8, 9.0, 13.8, 4.8], [2.65, 2.87, 2.71, 2.65], c='r') plt.plot([4.8, 11.9, 13.8, 4.8], [2.65, 3.06, 2.71, 2.65], c='g') plt.scatter([4.8], [2.65], s=50, c='r') plt.scatter([9.0], [...
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Here I use matrix inversion to "solve" the ternary plot for each lithologic component. Essentially each datapoint is a mix of the three components defined by the ternary diagram, with abundances of each defined by the relative distances from each endpoint. I use a GR cutoff of 40 API to determine when to use either the...
# QTZ-CAL-CLAY ur1 = inversion.UmaaRhomaa() ur1.set_dol_uma(11.9) ur1.set_dol_rhoma(3.06) # QTZ-CAL-DOL ur2 = inversion.UmaaRhomaa() df['UR_QTZ'] = np.nan df['UR_CLY'] = np.nan df['UR_CAL'] = np.nan df['UR_DOL'] = np.nan df.ix[df.GR >= 40, 'UR_QTZ'] = df.ix[df.GR >= 40].apply(lambda x: ur1.get_qtz(x.UMAA_EST, x.RHOMA...
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Plot facies by formation to see if the Formation feature will be useful
facies_colors = ['#F4D03F', '#F5B041','#DC7633','#6E2C00', '#1B4F72','#2E86C1', '#AED6F1', '#A569BD', '#196F3D'] fms = df.Formation.unique() fig, ax = plt.subplots(int(len(fms) / 2), 2, sharey=True, sharex=True, figsize=(5,10)) for i, fm in enumerate(fms): facies_counts = df[df.Formation == fm]['Facies'].value_coun...
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Group formations by similar facies distributions
fm_groups = [['A1 SH', 'B1 SH', 'B2 SH', 'B3 SH', 'B4 SH'], ['B5 SH', 'C SH'], ['A1 LM', 'C LM'], ['B1 LM', 'B3 LM', 'B4 LM'], ['B2 LM', 'B5 LM']] fm_group_dict = {fm:i for i, l in enumerate(fm_groups) for fm in l} df['FM_GRP'] = df.Formation.map(fm_group_dict)
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Make dummy variables from the categorical Formation feature
df = pd.get_dummies(df, prefix='FM_GRP', columns=['FM_GRP'])
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Compute Archie water saturation
def archie(df): return np.sqrt(0.08 / ((df.PHIND ** 2) * (10 ** df.ILD_log10))) df['SW'] = df.apply(lambda x: archie(x), axis=1)
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Get distances between wells
# modified from jesper latlong = pd.DataFrame({"SHRIMPLIN": [37.978076, -100.987305], # "ALEXANDER D": [37.6747257, -101.1675259], # "SHANKLE": [38.0633799, -101.3920543], # "LUKE G U": [37.4499614, -101.6121913], # "KIMZEY ...
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Add latitude and longitude as features, add distances to every other well as features
df['LAT'] = df.apply(lambda x: get_lat(x), axis=1) df['LON'] = df.apply(lambda x: get_long(x), axis=1) dist_dict = {} for k in latlong: dict_name = k + '_DISTANCES' k_dict = {} lat1 = latlong[k][0] lon1 = latlong[k][1] for l in latlong: lat2 = latlong[l][0] lon2 = latlong[l][1] ...
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
First guess at facies using KNN
df0 = df[(df.PHIND <= 40) & (df['Well Name'] != 'CROSS H CATTLE')] facies = df0['Facies'].values wells = df0['Well Name'].values keep_list0 = ['GR', 'ILD_log10', 'PHIND', 'PE', 'NM_M', 'RELPOS', 'RHOB_EST', 'UR_CLY', 'UR_CAL'] fv0 = df0[keep_list0].values clf0 = neighbors.KNeighborsClassifier(n_neigh...
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Fit RandomForect model and apply LeavePGroupsOut test There is some bad log data in this dataset which I'd guess is due to rugose hole. PHIND gets as high at 80%, which is certainly spurious, so I'll remove data with cross-plot porosity greater than 40% from the dataset. CROSS H CATTLE well also looks pretty different ...
df1 = df.dropna() df1 = df1[(df1['Well Name'] != 'CROSS H CATTLE') & (df.PHIND < 40.0)] facies = df1['Facies'].values wells = df1['Well Name'].values drop_list = ['Formation', 'Well Name', 'Facies', 'Depth', 'DPHI_EST', 'NPHI_EST', 'DeltaPHI', 'UMAA_EST', 'UR_QTZ', 'PE_EST', 'Recruit F9_DISTANCES', 'KIMZ...
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Apply model to validation dataset Load validation data (vd), build features, and use the classfier from above to predict facies. Ultimately the PE_EST curve seemed to be slightly more predictive than the PE curve proper (?). I use that instead of PE in the classifer so I need to compute it with the validation data.
# refit model to entire training set clf.fit(X, y) # load validation data vd = pd.read_csv('../validation_data_nofacies.csv') # compute extra log data features vd['DPHI_EST'] = vd.apply(lambda x: estimate_dphi(x), axis=1).astype(float) vd['RHOB_EST'] = vd.apply(lambda x: estimate_rhob(x), axis=1) vd['NPHI_EST'] = vd....
dagrha/RFC_submission_3_dagrha.ipynb
seg/2016-ml-contest
apache-2.0
Для 61 большого города в Англии и Уэльсе известны средняя годовая смертность на 100000 населения (по данным 1958–1964) и концентрация кальция в питьевой воде (в частях на миллион). Чем выше концентрация кальция, тем жёстче вода. Города дополнительно поделены на северные и южные.
water_data = pd.read_table('water.txt') water_data.info() water_data.describe() water_data.head()
4 Stats for data analysis/Homework/1 test mean conf int/Test Mean conf int.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Постройте 95% доверительный интервал для средней годовой смертности в больших городах. Чему равна его нижняя граница? Округлите ответ до 4 знаков после десятичной точки.
mort_mean = water_data['mortality'].mean() print('Mean mortality: %f' % mort_mean) from statsmodels.stats.weightstats import _tconfint_generic mort_mean_std = water_data['mortality'].std() / np.sqrt(water_data['mortality'].shape[0]) print('Mortality 95%% interval: %s' % str(_tconfint_generic(mort_mean, mort_mean_std...
4 Stats for data analysis/Homework/1 test mean conf int/Test Mean conf int.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
На данных из предыдущего вопроса постройте 95% доверительный интервал для средней годовой смертности по всем южным городам. Чему равна его верхняя граница? Округлите ответ до 4 знаков после десятичной точки.
water_data_south = water_data[water_data.location == 'South'] mort_mean_south = water_data_south['mortality'].mean() print('Mean south mortality: %f' % mort_mean_south) mort_mean_south_std = water_data_south['mortality'].std() / np.sqrt(water_data_south['mortality'].shape[0]) print('Mortality south 95%% interval: %s' ...
4 Stats for data analysis/Homework/1 test mean conf int/Test Mean conf int.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
На тех же данных постройте 95% доверительный интервал для средней годовой смертности по всем северным городам. Пересекается ли этот интервал с предыдущим? Как вы думаете, какой из этого можно сделать вывод?
water_data_north = water_data[water_data.location == 'North'] mort_mean_north = water_data_north['mortality'].mean() print('Mean north mortality: %f' % mort_mean_north) mort_mean_north_std = water_data_north['mortality'].std() / np.sqrt(water_data_north['mortality'].shape[0]) print('Mortality north 95%% interval: %s' ...
4 Stats for data analysis/Homework/1 test mean conf int/Test Mean conf int.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Пересекаются ли 95% доверительные интервалы для средней жёсткости воды в северных и южных городах?
hardness_mean_south = water_data_south['hardness'].mean() print('Mean south hardness: %f' % hardness_mean_south) hardness_mean_north = water_data_north['hardness'].mean() print('Mean north hardness: %f' % hardness_mean_north) hardness_mean_south_std = water_data_south['hardness'].std() / np.sqrt(water_data_south['har...
4 Stats for data analysis/Homework/1 test mean conf int/Test Mean conf int.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
<b> Вспомним формулу доверительного интервала для среднего нормально распределённой случайной величины с дисперсией σ2: При σ=1 какой нужен объём выборки, чтобы на уровне доверия 95% оценить среднее с точностью ±0.1?
from scipy import stats np.ceil((stats.norm.ppf(1-0.05/2) / 0.1)**2)
4 Stats for data analysis/Homework/1 test mean conf int/Test Mean conf int.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this data, 15,000 images for each label (A-J).
def download(url, file): """ Download file from <url> :param url: URL to file :param file: Local file path """ if not os.path.isfile(file): print('Downloading ' + file + '...') urlretrieve(url, file) print('Download Finished') # Download the training and test dataset. do...
intro-to-tensorflow/intro_to_tensorflow.ipynb
snegirigens/DLND
mit
<img src="image/Mean_Variance_Image.png" style="height: 75%;width: 75%; position: relative; right: 5%"> Problem 1 The first problem involves normalizing the features for your training and test data. Implement Min-Max scaling in the normalize_grayscale() function to a range of a=0.1 and b=0.9. After scaling, the values ...
# Problem 1 - Implement Min-Max scaling for grayscale image data def normalize_grayscale(image_data): """ Normalize the image data with Min-Max scaling to a range of [0.1, 0.9] :param image_data: The image data to be normalized :return: Normalized image data """ # TODO: Implement Min-Max scaling...
intro-to-tensorflow/intro_to_tensorflow.ipynb
snegirigens/DLND
mit
Checkpoint All your progress is now saved to the pickle file. If you need to leave and comeback to this lab, you no longer have to start from the beginning. Just run the code block below and it will load all the data and modules required to proceed.
%matplotlib inline # Load the modules import pickle import math import numpy as np import tensorflow as tf from tqdm import tqdm import matplotlib.pyplot as plt # Reload the data pickle_file = 'notMNIST.pickle' with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f) train_features = pickle_data['train_da...
intro-to-tensorflow/intro_to_tensorflow.ipynb
snegirigens/DLND
mit
Problem 2 Now it's time to build a simple neural network using TensorFlow. Here, your network will be just an input layer and an output layer. <img src="image/network_diagram.png" style="height: 40%;width: 40%; position: relative; right: 10%"> For the input here the images have been flattened into a vector of $28 \time...
# All the pixels in the image (28 * 28 = 784) features_count = 784 # All the labels labels_count = 10 # TODO: Set the features and labels tensors features = tf.placeholder (tf.float32, [None, features_count]) labels = tf.placeholder (tf.float32, [None, labels_count]) # TODO: Set the weights and biases tensors weights...
intro-to-tensorflow/intro_to_tensorflow.ipynb
snegirigens/DLND
mit
<img src="image/Learn_Rate_Tune_Image.png" style="height: 70%;width: 70%"> Problem 3 Below are 2 parameter configurations for training the neural network. In each configuration, one of the parameters has multiple options. For each configuration, choose the option that gives the best acccuracy. Parameter configurations:...
# Change if you have memory restrictions batch_size = 128 # TODO: Find the best parameters for each configuration epochs = 1 learning_rate = 0.5 ### DON'T MODIFY ANYTHING BELOW ### # Gradient Descent optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) # The accuracy measured against the v...
intro-to-tensorflow/intro_to_tensorflow.ipynb
snegirigens/DLND
mit
Test You're going to test your model against your hold out dataset/testing data. This will give you a good indicator of how well the model will do in the real world. You should have a test accuracy of at least 80%.
### DON'T MODIFY ANYTHING BELOW ### # The accuracy measured against the test set test_accuracy = 0.0 with tf.Session() as session: session.run(init) batch_count = int(math.ceil(len(train_features)/batch_size)) for epoch_i in range(epochs): # Progress bar batches_pbar = tqdm(r...
intro-to-tensorflow/intro_to_tensorflow.ipynb
snegirigens/DLND
mit
I'll write another function to grab batches out of the arrays made by split data. Here each batch will be a sliding window on these arrays with size batch_size X num_steps. For example, if we want our network to train on a sequence of 100 characters, num_steps = 100. For the next batch, we'll shift this window the next...
def get_batch(arrs, num_steps): batch_size, slice_size = arrs[0].shape n_batches = int(slice_size/num_steps) for b in range(n_batches): yield [x[:, b*num_steps: (b+1)*num_steps] for x in arrs] def build_rnn(num_classes, batch_size=50, num_steps=50, lstm_size=128, num_layers=2, le...
tensorboard/Anna_KaRNNa_Name_Scoped.ipynb
retnuh/deep-learning
mit
Write out the graph for TensorBoard
model = build_rnn(len(vocab), batch_size=batch_size, num_steps=num_steps, learning_rate=learning_rate, lstm_size=lstm_size, num_layers=num_layers) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) ...
tensorboard/Anna_KaRNNa_Name_Scoped.ipynb
retnuh/deep-learning
mit
Training Time for training which is is pretty straightforward. Here I pass in some data, and get an LSTM state back. Then I pass that state back in to the network so the next batch can continue the state from the previous batch. And every so often (set by save_every_n) I calculate the validation loss and save a checkpo...
!mkdir -p checkpoints/anna epochs = 10 save_every_n = 200 train_x, train_y, val_x, val_y = split_data(chars, batch_size, num_steps) model = build_rnn(len(vocab), batch_size=batch_size, num_steps=num_steps, learning_rate=learning_rate, lstm_size=...
tensorboard/Anna_KaRNNa_Name_Scoped.ipynb
retnuh/deep-learning
mit
Model Inputs First we need to create the inputs for our graph. We need two inputs, one for the discriminator and one for the generator. Here we'll call the discriminator input inputs_real and the generator input inputs_z. We'll assign them the appropriate sizes for each of the networks. Exercise: Finish the model_inpu...
def model_inputs(real_dim, z_dim): inputs_real = tf.placeholder(tf.float32,(None,real_dim),name='input_real') inputs_z = tf.placeholder(tf.float32,(None,z_dim),name='input_z') return inputs_real, inputs_z
gan_mnist/Intro_to_GANs_Exercises.ipynb
ClementPhil/deep-learning
mit
Generator network Here we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero ...
def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01): ''' Build the generator network. Arguments --------- z : Input tensor for the generator out_dim : Shape of the generator output n_units : Number of units in hidden layer reuse : Reuse the variables...
gan_mnist/Intro_to_GANs_Exercises.ipynb
ClementPhil/deep-learning
mit
Discriminator The discriminator network is almost exactly the same as the generator network, except that we're using a sigmoid output layer. Exercise: Implement the discriminator network in the function below. Same as above, you'll need to return both the logits and the sigmoid output. Make sure to wrap your code in a...
def discriminator(x, n_units=128, reuse=False, alpha=0.01): with tf.variable_scope('discriminator',reuse=reuse): # finish this # Hidden layer h1 = tf.contrib.layers.fully_connected(x,n_units,activation_fn=None) # Leaky ReLU h1 = tf.maximum(alpha * h1,h1) logits = tf....
gan_mnist/Intro_to_GANs_Exercises.ipynb
ClementPhil/deep-learning
mit
Build network Now we're building the network from the functions defined above. First is to get our inputs, input_real, input_z from model_inputs using the sizes of the input and z. Then, we'll create the generator, generator(input_z, input_size). This builds the generator with the appropriate input and output sizes. Th...
tf.reset_default_graph() # Create our input placeholders input_real, input_z = model_inputs(input_size, z_size) # Generator network here g_model,g_logits = generator(input_z, input_size) # g_model is the generator output # Disriminator network here d_model_real, d_logits_real = discriminator(input_real) d_model_fake,...
gan_mnist/Intro_to_GANs_Exercises.ipynb
ClementPhil/deep-learning
mit
Discriminator and Generator Losses Now we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, d_loss = d_loss_real + d_loss_fake. The losses will by sigmoid cross-entropies, which we can get with tf.nn.sigmoid_cross_entropy_wit...
# Calculate losses d_loss_real = d_loss_fake = d_loss = g_loss =
gan_mnist/Intro_to_GANs_Exercises.ipynb
ClementPhil/deep-learning
mit
We start by making sure the computation is performed on GPU if available. prefer_gpu should be called right after importing Thinc, and it returns a boolean indicating whether the GPU has been activated.
from thinc.api import prefer_gpu prefer_gpu()
examples/03_pos_tagger_basic_cnn.ipynb
explosion/thinc
mit
We also define the following helper functions for loading the data, and training and evaluating a given model. Don't forget to call model.initialize with a batch of input and output data to initialize the model and fill in any missing shapes.
import ml_datasets from tqdm.notebook import tqdm from thinc.api import fix_random_seed fix_random_seed(0) def train_model(model, optimizer, n_iter, batch_size): (train_X, train_y), (dev_X, dev_y) = ml_datasets.ud_ancora_pos_tags() model.initialize(X=train_X[:5], Y=train_y[:5]) for n in range(n_iter): ...
examples/03_pos_tagger_basic_cnn.ipynb
explosion/thinc
mit