id
int64
0
25.6k
text
stringlengths
0
4.59k
16,200
ost popular artist the next information the readers may be interested in iswho are the most popular artists in the datasetthe code to plot this information is quite similar to the code given previouslyso we will not include the exact code snippet the resultant graph is shown in figure - figure - most popular artists we...
16,201
another slightly off reading is that coldplay is the most popular artistbut they don' have candidate in the most popular songs list this indirectly hints at an even distribution of those play counts across all of their tracks you can take it as exercise to determine song play distribution for each of the artists who ap...
16,202
figure - distribution of play counts for users given the nature of the datawe can perform large variety of cool visualizationsfor exampleplotting how the top tracks of artists are playedthe play count distribution on yearly basisetc but we believe by now you are sufficiently skilled in both the art of asking pertinent ...
16,203
types of recommendation engines the major area of distinction in different recommendation engines comes from the entity that they assume is the most important in the process of generating recommendations there are different options for choosing the central entity and that choice will determine the type of recommendati...
16,204
popularity-based recommendation engine the simplest recommendation engine is naturally the easiest to develop as we can easily develop recommendation enginesthis type of recommendation engine is very straightforward one to develop the driving logic of this recommendation engine is that if some item is liked (or listen...
16,205
figure - recommendation by the popularity recommendation engine item similarity based recommendation engine in the last sectionwe witnessed one of the simplest recommendation engines in this section we deal with slightly more complex solution this recommendation engine is based on calculating similarities between user...
16,206
determine the songs listened to by the user calculate the similarity of each song in the user' list to those in our datasetusing the similarity metric defined previously determine the songs that are most similar to the songs already listened to by the user select subset of these songs as recommendation based on the sim...
16,207
figure - recommendation by the item similarity based recommendation engine ##note at the start of this sectionwe mentioned we don' readily have access to song' features that we can use to define similarity as part of the million song databasewe have those features available for each of the songs in the dataset you are ...
16,208
the starting point of any matrix factorization-based method is the utility matrixas shown in table - the utility matrix is matrix of user item dimension in which each row represents user and each column stands for an item table - example of utility matrix item user item item user user item item notice that we have lot ...
16,209
we can also try to explain the concept of matrix factorization as an image based on figure - we can regenerate the original matrix by multiplying the two matrices together to make recommendation to the userwe can multiply the corresponding user' row from the first matrix by the item matrix and determine the items from ...
16,210
the modified dataframe is shown in figure - figure - dataset with implicit feedback the next transformation of data that is required is to convert our dataframe into numpy matrix in the format of utility matrix we will convert our dataframe into sparse matrixas we will have lot of missing values and sparse matrices are...
16,211
in [ ] = #initialize sample user rating matrix urm data_sparse max_pid urm shape[ max_uid urm shape[ #compute svd of the input user ratings matrix usvt compute_svd(urmkutest [ #get estimated rating for test user print("predicted ratings:"utest_recommended_items compute_estimated_matrix(urmusvtutestktruefor user in utes...
16,212
 note on recommendation engine libraries you might have noticed that we did not use any readily available packages for building our recommendation system like for every possible taskpython has multiple libraries available for building recommendation engines too but we have refrained from using such libraries because w...
16,213
forecasting stock and commodity prices in the so farwe covered variety of concepts and solved diverse real-world problems in this we will dive into forecast/prediction use cases predictive analytics or modeling involves concepts from data miningadvanced statisticsmachine learningand so on to model historical data to fo...
16,214
for prediction/forecasting use cases is termed as time series forecasting though in generalboth schools of thought utilize the same set of tools and techniques it is more about how the concepts are grouped for structured learning and application ##note time series and its analysis is complete field of study on its own ...
16,215
figure - web site visits per day time series components the time series at hand is data related to web site visits per day for given web site as mentioned earliertime series analysis deals with understanding the underlying structure and forces that result in the series as we see it let' now try to deconstruct various ...
16,216
index=pd date_rangeinput_df date_of_visit min()input_df date_of_visit max()freq=' 'deompose seasonal_decompose(ts_visits interpolate()freq= deompose plot(we first create pandas series object with additional care taken to set the frequency of the time series index it is important to note that statsmodels has number of t...
16,217
smoothing techniques as discussed in the previous preprocessing the raw data depends upon the data as well as the use case requirements yet there are certain standard preprocessing techniques for each type of data unlike the datasets we have seen so farwhere we consider each observation to be independent of other (pas...
16,218
figure - smoothening using moving average the plot in figure - shows the smoothened visits time series the smoothened series captures the overall structure of the original series all the while reducing the random variation in it you are encouraged to explore and experiment with different window sizes and compare the re...
16,219
exponential smoothening is also called exponentially weighted moving average or ewma for short single exponential smoothening is one of the simplest to get started with the general formula is given as et yt - ( et - whereet is the th smoothened observationy is the actual observed value at - instanceand is smoothing con...
16,220
in the coming sectionswe will apply our understanding of time seriespreprocessing techniquesand so on to solve stock and commodity price forecasting problems using different forecasting methods forecasting gold price goldthe yellow shiny metalhas been the fancy of mankind since ages from making jewelry to being used a...
16,221
##note causal or cross-sectional forecasting/modeling is where the target variable has relationship with one or more predictor variablesexample regression models (see time series forecasting is about forecasting variable(sthat is changing over time both these techniques are grouped under quantitative techniques as ment...
16,222
wherext is the observation at time tet is the noise and ae aqi = the dependency on prior values is denoted by or the order of ar model moving average or ma modelingis again essentially linear regression model that models the impact of noise/error from prior observations to current one the model is denoted as - / jqe - ...
16,223
the plot in figure - shows general upward trend with sudden rise in the and then near figure - gold prices over the years since stationarity is one of the primary assumptions of arima modelswe will utilize augmented dickey fuller test to check our series for stationarity the following snippet helps us calculate the ad ...
16,224
if the test statistic of ad fuller test is less than the critical value( )we reject the null hypothesis of nonstationarity the ad fuller test is available as part of the statsmodel library since it is quite evident that our original series of gold prices is non-stationarywe will perform log transformation and see if we...
16,225
the plot points out time varying mean of the series and hence the non-stationarity as discussed in the key conceptsdifferencing series helps in achieving stationarity in the following snippetwe prepare first order differenced log series and perform the same tests in [ ]log_series_shift log_series log_series shift(log_s...
16,226
building an arima model requires some experience and intuition as compared other models identifying pdand parameters of the model can be done using different methodsthough arriving at the right set of numbers is dependent both upon requirements and experience one of the commonly used methods is the plotting of acf and ...
16,227
figure - acf and pacf plots the acf and pacf plot also help us understand if series is stationary or not if series has gradually decreasing values for acf and pacfit points toward non-stationarity property in the series ##note identifying the pdand values for any arima model is as much science as it is art more details...
16,228
figure - auto arima similar to our findings using acf-pacfauto arima suggests that the best fitting model is arima( , , based upon the aic criteria note that aic or akaike information criterion measures the goodness of fit and parsimony it is relative metric and does not point toward quality of models in an absolute se...
16,229
figure - the forecast plot for arima( , , as evident from the plot in figure - the model captures the overall upward trend though it misses out on the sudden jump in values around yet it seems to give pretty nice idea of what can be achieved using this methodology the arima_gridsearch_cv(function produces similar stati...
16,230
in this sectionwe learn how to apply recurrent neural networks (rnnsto the problem of stock price prediction and understand the intricacies problem statement stock price prediction is the task of forecasting the future value of given stock given the historical daily close price for & indexprepare and compare forecasti...
16,231
the plot in figure - shows that we have closing price information available since up until recently kindly note that the same information is also available through quandl (which we used in the previous section to get gold price informationyou may use the same to get this data as well recurrent neural networkslstm arti...
16,232
for stock price predictionwe will utilize lstm units to implement an rnn model rnns are typically useful in sequence modeling applicationssome of them are as followssequence classification tasks like sentiment analysis of given corpus (see for the detailed use casesequence tagging tasks like pos tagging given sentence ...
16,233
figure - rolling/sliding windows from original time series for the hands-on examples in this sectionyou can refer to the jupyter notebook notebook_stock_prediction_regression_modeling_lstm ipynb for the necessary code snippets and examples for using lstms to model our time serieswe need to apply one more level of trans...
16,234
scale data in - range scaler none if scalescaler=minmaxscaler(feature_range=( )train scaler fit_transform(traintest scaler transform(testsplit independent and dependent variables x_train train[::- y_train train[:- x_test test[::- y_test test[:- transforms for lstm input x_train np reshape(x_train(x_train shape[ ]x_trai...
16,235
x_train shape=( y_train shape=( ,x_test shape=( y_test shape=( ,the x_train and x_test tensors conform to the (nwfformat we discussed earlier and is required for input to our rnn we have sequences in our training seteach with six time steps and one value to forecast similarlywe have sequences in our test set now that w...
16,236
the function is available in the script lstm_utils py the following snippet uses the predict_reg_ multiple(function to get predictions on the test set in [ test_pred_seqs predict_reg_multiple(lstm_modelx_testwindow_size=windowprediction_len=pred_lengthto analyze the performancewe will calculate the rmse for the fitted ...
16,237
sequence modeling in the previous section we modeled our time series like regression use case in essencethe problem formulation though utilized past window to forecastit did not use the time step information in this sectionwe will solve the same stock prediction problem using lstms by modeling it as sequence for the h...
16,238
print("train_y shape={}format(train_y shape)print("test_x shape={}format(test_x shape)print("test_y shape={}format(test_y shape)data split complete train_x shape=( train_y shape=( test_x shape=( test_y shape=( having prepared the datasetslet we'll now move onto setting up the rnn network since we are planning on genera...
16,239
we have our dataset preprocessed and split into train and test along with model object using the function get_seq_model(the next step is to simply train the model using the fit(function while modeling stock price information as sequencewe are assuming the whole time series as one big sequence hencewhile training the mo...
16,240
forecast values testpredict seq_lstm_model predict(testpredictevaluate performance testscore math sqrt(mean_squared_error(test_y[ ]testpredict[ ][:test_x shape[ ]])print('test score rmse(testscore)test score rmse we can perform the same steps on the training set as well and check the performance while generating the tr...
16,241
the forecast plot in figure - shows promising picture we can see that the training fit is nearly perfect which is kind of expected the testing performance or the forecast also shows decent performance even though the forecast deviates from the actual at placesthe overall performance both in terms of rmse and the fit se...
16,242
prepare train and test sets train_size int(prophet_df shape[ ]* train_df prophet_df ix[:train_sizetest_df prophet_df ix[train_size+ :once we have the datasets preparedwe create an object of the prophet class and simply fit the model using fit(function kindly note that the model expects the time series value to be in co...
16,243
the model' forecasts are bit off the mark (see figure - )but the exercise clearly demonstrates the possibilities here the forecast dataframe provides even more details about seasonalityweekly trendsand so on you are encouraged to explore this further prophet is based upon stan stan is statistical modeling language/fram...
16,244
deep learning for computer vision deep learning is not just keyword abuzz in the industry and academicsit has thrown wide open whole new field of possibilities deep learning models are being employed in all sorts of use cases and domainssome of which we saw in the previous deep neural networks have tremendous potential...
16,245
we touched upon the concepts of cnns in (in the section "deep learning"and (in the section :feature engineering on image datahoweveras quick refresherthe following are the key concepts worth reiteratingconvolutional layerthis is the key differentiating component of cnn as compared to other neural networks convolutional...
16,246
image classification with cnns convolutional neural networks are prime examples of the potential and power of neural networks to learn detailed feature representations and patterns from images and perform complex tasksranging from object recognition to image classification and many more cnns have gone through tremendo...
16,247
cnn based deep learning classifier from scratch similar to any machine learning algorithmneural networks also require the input data to be certain shapesizeand type sobefore we reach the modeling stepthe first thing is to preprocess the data itself the following snippet gets the dataset and then performs one hot encod...
16,248
the next step involves compiling we use categorical_crossentropy as our loss function since we are dealing with multiple classes besides thiswe use the adadelta optimizer and then train the classifier on the training data the following snippet showcases the same in [ ]model compile(loss=keras losses categorical_crossen...
16,249
figure - sample image from the cifar dataset sample flow of how an image is viewed by the cnn is explained in the notebook notebook_cnn_cifar _classifier ipynb it contains rest of the code discussed in this section figure - shows an image from the test dataset it looks like ship and the model correctly identifies the s...
16,250
we also recommend you go through the section "automated feature engineering with deep learningin to learn more about extracting feature representations from images using convolutional layers cnn based deep learning classifier with pretrained models building classifier from scratch has its own set of pros and cons yeta...
16,251
in [ ]from keras import applications vgg_model applications vgg (include_top=falseweights='imagenet'now that the pre-trained model is availablewe will utilize it to extract features from our training dataset remember vgg- is trained upon imagenet while we would be using cifar to build classifier since imagenet contains...
16,252
block _conv (conv (nonenonenone block _conv (conv (nonenonenone block _pool (maxpooling (nonenonenone ================================================================total params , , trainable params , , non-trainable params from the preceding outputyou can see that the architecture is huge with lot of layers figure - ...
16,253
these features are widely known as bottleneck features due to the fact that there is an overall decrease in the volume of the input data points it would be worth exploring the model summary to understand how the vgg model transforms the data the output of this stage (the bottleneck featuresis used as input to the class...
16,254
print("actual class:{}format(np nonzero(y_test[img_idx])[ ][ ])test_image =np expand_dims(x_test[img_idx]axis= bf vgg_model predict(test_image,verbose= pred_label clf_model predict_classes(bf,batch_size= ,verbose= print("predicted class:{}format(pred_label[ ])if show_probaprint("predicted probabilities"print(clf_model ...
16,255
figure - left imagethe original photograph depicting the neckarfront in tubingengermany right imagethe painting (insetthe starry night by vincent van goghthat provided the style for the respective generated image sourcea neural algorithm of artistic stylegatys et al (arxiv: the results in figure - showcase how painting...
16,256
thusfor the overall process of neural style transferwe have an overall loss functionwhich can be defined as combination of content and style loss functions lstyle transfer argming(alcontent(cgblstyle(sg)where and are weights used to control the impact of content and style components on the overall loss the loss functio...
16,257
[:: + [:: + 'bgr'->'rgbx [::::- np clip( astype('uint 'return as we would be writing custom loss functions and manipulation routineswe would need to define certain placeholders keras is high-level library that utilizes tensor manipulation backends (like tensorflowtheanoand cntkto perform the heavy lifting thusthese pla...
16,258
loss functions as discussed in the background subsectionthe problem of neural style transfer revolves around loss functions of content and style in this subsectionwe will discuss and define the required loss functions content loss in any cnn-based modelactivations from top layers contain more global and abstract info...
16,259
total variation loss it was observed that optimization to reduce only the style and content losses led to highly pixelated and noisy outputs to cover the sametotal variation loss was introduced the total variation loss is analogous to regularization loss this is introduced for ensuring spatial continuity and smoothnes...
16,260
set the source research paper followed and set the content and style layers source_paper 'gatyscontent_layerstyle_layers set_cnn_layers(source=source_paper#build the weighted loss function initialize total loss loss variable( add content loss layer_features layers[content_layertarget_image_features layer_features[ :::c...
16,261
def loss(selfx)assert self loss_value is none reshape(( self heightself width )outs fetch_loss_and_grads([ ]loss_value outs[ grad_values outs[ flatten(astype('float 'self loss_value loss_value self grad_values grad_values return self loss_value def grads(selfx)assert self loss_value is not none grad_values np copy(self...
16,262
print('current loss value:'min_valif ( + = or = save current generated image only every iterations img copy(reshape((img_heightimg_width )img deprocess_image(imgfname result_prefix '_at_iteration_% png%( + imsave(fnameimgprint('image saved as'fnameend_time time time(print('iteration % completed in %ds( + end_time start...
16,263
##note the style we use for our first imagedepicted in figure - is named edtaonisl this is master piece by francis picabia through this oil painting francis picabia pioneered new visual language more details about this painting are available at we utilize matplotlib and skimage libraries to load and understand the styl...
16,264
ax set_title('iteration 'ax fig add_subplot( , ax imshow(cr_iter ax set_title('iteration ' fig suptitle('city road image after style transfer'figure - the city road image style transfer at the firsttenthand twentieth iteration the results depicted in figure - sure seem pleasant and amazing it is quite apparent how the ...
16,265
figure - italian street image style transfer at the firsttenth and twentieth iteration the results depicted in figure - are definitely pleasure to look at and give the feeling of an entire city underwaterwe encourage you to use images of your own with this same framework also feel free to experiment with leveraging dif...
16,266
advanced supervised deep learning models dense layer embedding layer lstm-based classification model lstm cell architecture data flow model performance metricslstm most_common(countfunction norm_train_reviews and norm_test_reviews pad_index parametersembedding layer rnn and lstm unitsstructure text sentiment class labe...
16,267
bike sharing dataset (cont outliers - preprocessing - linear regression - modeling (see modelingbike sharing datasetproblem statement regression analysis assumptions cross validation normality test - residual analysis -squared types binary classification model bin-counting scheme bing liu' lexicon binning image intensi...
16,268
two-layer pooling stride visualizing cross industry standard process for data mining (crisp-dmprocess model assessment stage attribute generation building machine intelligence business context and requirements business problem data collection data description data integration data mining lifecycle - data mining problem...
16,269
data wrangling (cont product purchase transactions dataset attributes/features/properties - categorical data - duplicates filtering data missing values - normalization process string data transformations - typecasting date-based features decision tree decision tree based regression algorithms hyperparameters - node spl...
16,270
robust standardized feature selection methods figure module axes objects cosine curve - sine curve - filter methods fine-tuning pre-trained models fixed-width binning - forecasting gold price dataset modeling acf and pacf plots arima( , , ) arima_grid_search_cv() forecast(method mean and standard deviation plot - plotg...
16,271
for support files and downloads related to your bookplease visit xxx bdlu vcdpn did you know that packt offers ebook versions of every book publishedwith pdf and epub files availableyou can upgrade to the ebook version at xxx bdlu vcdpnand as print book customeryou are entitled to discount on the ebook copy get in ...
16,272
thanks for purchasing this packt book at packtquality is at the heart of our editorial process to help us improveplease leave us an honest review on this book' amazon page at iuuqt xxxbnb[podpneq if you' like to join our team of regular reviewersyou can email us at dvtupnfssfwjfxt!qbdluqvcdpn we award o...
16,273
preface getting started installing enthought canopy giving the installation test run if you occasionally get problems opening your ipnyb files using and understanding ipython (jupyternotebooks python basics part understanding python code importing modules data structures experimenting with lists pre colon post colon ne...
16,274
summary statistics and probability refresherand python practice types of data numerical data discrete data continuous data categorical data ordinal data meanmedianand mode mean median the factor of outliers mode using meanmedianand mode in python calculating mean using the numpy package visualizing data using matplotli...
16,275
percentiles quartiles computing percentiles in python moments computing moments in python summary matplotlib and advanced probability concepts crash course in matplotlib generating multiple plots on one graph saving graphs as images adjusting the axes adding grid changing line types and colors labeling axes and adding ...
16,276
the co-efficient of determination or -squared computing -squared interpreting -squared computing linear regression and -squared using python activity for linear regression polynomial regression implementing polynomial regression using numpy computing the -squared error activity for polynomial regression multivariate re...
16,277
activity summary recommender systems what are recommender systemsuser-based collaborative filtering limitations of user-based collaborative filtering item-based collaborative filtering understanding item-based collaborative filtering how item-based collaborative filtering workscollaborative filtering using python findi...
16,278
dealing with real-world data bias/variance trade-off -fold cross-validation to avoid overfitting example of -fold cross-validation using scikit-learn data cleaning and normalisation cleaning web log data applying regular expression on the web log modification one filtering the request field modification two filtering p...
16,279
using map(actions introducing mllib some mllib capabilities special mllib data types the vector data type labeledpoint data type rating data type decision trees in spark with mllib exploring decision trees code creating the sparkcontext importing and cleaning our data creating test candidate and building our decision t...
16,280
running / test on some experimental data when there' no real difference between the two groups does the sample size make differencesample size increased to six-digits sample size increased seven-digits / testing determining how long to run an experiment for / test gotchas novelty effects seasonal effects selection bias...
16,281
being data scientist in the tech industry is one of the most rewarding careers on the planet today went and studied actual job descriptions for data scientist roles at tech companies and distilled those requirements down into the topics that you'll see in this course hands-on data science and python machine learning is...
16,282
who this book is for if you are budding data scientist or data analyst who wants to analyze and gain actionable insights from data using pythonthis book is for you programmers with some experience in python who want to enter the lucrative world of data science will also find this book to be very useful conventions in t...
16,283
new terms and important words are shown in bold words that you see on the screenfor examplein menus or dialog boxesappear in the text like this"on windows you'll need to open up the start menu and go to windows system control panel to open up control panel warnings or important notes appear like this tips and tricks ap...
16,284
you can download the code files by following these steps log in or register to our website using your email address and password hover the mouse pointer on the support tab at the top click on code downloads errata enter the name of the book in the search box select the book for which you're looking to download the code...
16,285
errata although we have taken every care to ensure the accuracy of our contentmistakes do happen if you find mistake in one of our books-maybe mistake in the text or the codewe would be grateful if you could report this to us by doing soyou can save other readers from frustration and help us improve subsequent versions...
16,286
getting started since there' going to be code associated with this book and sample data that you need to get as welllet me first show you where to get that and then we'll be good to go we need to get some setup out of the way first first things firstlet' get the code and the data that you need for this book so you can ...
16,287
installing enthought canopy let' dive right in and get what you need installed to actually develop python code with data science on your desktop ' going to walk you through installing package called enthought canopy which has both the development environment and all the python packages you need pre-installed it makes l...
16,288
to get canopy installedjust go to xxxfouipvhiudpn and click on downloadscanopy[
16,289
enthought canopy is freefor the canopy express edition which is what you want for this book you must then select your operating system and architecture for methat' windows -bitbut you'll want to click on corresponding download button for your operating system and with the python option we don' have to give them any per...
16,290
after that' downloaded we go ahead and open up the canopy installerand run ityou might want to read the license before you agree to itthat' up to youand then just wait for the installation to complete once you hit the finish button at the end of the install processallow it to launch canopy automatically you'll see that...
16,291
the beautiful thing is that pretty much everything you need for this book comes pre-installed with enthought canopythat' why recommend using it there is just one last thing we need to set upso go ahead and click the editor button there on the canopy welcome screen you'll then see the editor screen come upand if you cli...
16,292
let me show you how that works if you now open window in your operating system to view the accompanying book files that you downloadedas described in the preface of this book it should look something like thiswith the set of jqzoc code files you downloaded for this book
16,293
now go down to the outliers file in the listthat' the vumjfstjqzoc filedouble-click itand what should happen is it' going to start up canopy first and then it' going to kick off your web browserthis is because ipython/jupyter notebooks actually live within your web browser there can be small pause at firstand it can b...
16,294
if you occasionally get problems opening your ipnyb files just occasionallyi've noticed that things can go little bit wrong when you double-click on jqzoc file don' panicjust sometimescanopy can get little bit flakyand you might see screen that is looking for some password or tokenor you might occasionally see screen ...
16,295
now what' going to happen when we double-click on this ipython jqzoc file is that first of all it' going to spark up canopyif it' not sparked up alreadyand then it' going to launch web browser this is how the full vumjfst notebook webpage looks within my browser
16,296
as you can see herenotebooks are structured in such way that can intersperse my little notes and commentary about what you're seeing here within the actual code itselfand you can actually run this code within your web browsersoit' very handy format for me to give you sort of little reference that you can use later on i...
16,297
hitting the run button with the code block selectedwill cause this graph to be regeneratedsimilarlywe can click on the next code block little further downyou'll spot the one which has the following single line of code jodpnftnfbo if you select the code block containing this lineand hit the run button to run the codeyo...
16,298
let' keep going and have some fun in the next code block downyou'll see the following codewhich tries to detect outliers like donald trump and remove them from the datasetefgsfkfdu@pvumjfst ebub oqnfejbo ebub oqtue ebub gjmufsfe sfuvsogjmufsfe gjmufsfe sfkfdu@pvumjfst jodpnft qmuijtu gjmufsfeqmutipx so select the...
16,299
python basics part if you already know pythonyou can probably skip the next two sections howeverif you need refresheror if you haven' done python beforeyou'll want to go through these there are few quirky things about the python scripting language that you need to knowso let' dive in and just jump into the pool and lea...