concept number in category machine learning

appears as: numbers, The number, number, numbers, number, The numbers, The number, A number
Machine Learning with TensorFlow, Second Edition

This is an excerpt from Manning's book Machine Learning with TensorFlow, Second Edition.

  • Vectors have a flat and simple structure and are the typical embodiment of data in most real-world machine-learning applications and scalars are a single element in the vector. Vectors have two attributes: a natural number representing the dimension of the vector, and a type (such as real numbers, integers, and so on). Just as a refresher, some examples of two-dimensional vectors of integers are (1, 2) and (–6, 0) and similarly a scalar could be 1, or the character ‘a.’ Some examples of three-dimensional vectors of real numbers are (1.1, 2.0, 3.9) and (п, п/2, п/3). You get the idea: a collection of numbers of the same type. In a program that uses machine learning, a vector measures a property of the data, such as color, density, loudness, or proximity—anything you can describe with a series of numbers, one for each thing being measured.
  • A quick and dirty heuristic you can use to compare the flexibility of two machine-learning models is to count the number of parameters to be learned. As shown in figure 14.1, a fully connected neural network that takes in a 256 × 256 image and maps it to a layer of 10 neurons will have 256 × 256 × 10 = 655,360 parameters! Compare that to a model with perhaps only 5 parameters. It’s likely that the fully connected neural network can represent more-complex data than the model with 5 parameters.

    Figure 14.1 In a fully connected network, each pixel of an image is treated as an input. For a grayscale image of size 256 × 256, that’s 256 × 256 neurons! Connecting each neuron to 10 outputs yields 256 × 256 × 10 = 655,360 weights.

    The next section introduces convolutional neural networks, which are a clever way to reduce the number of parameters. Instead of dealing with a fully connected network that would have to learn many more parameters individually, the CNN approach reuses the same parameter multiple times reducing the number of learned weights.

    The beauty of the CNN is that the number of parameters is independent of the size of the original image. You can run the same CNN on a 300 × 300 image, and the number of parameters won’t change in the convolution layer!

    Grokking Machine Learning

    This is an excerpt from Manning's book Grokking Machine Learning.

    Rule 6: Consider the number of the day, where Monday is 0, Tuesday is 1, Wednesday is 2, Thursday is 3, Friday is 4, Saturday is 5, and Sunday is 6. If we add the number of the day and the size of the email (in KB), and the result is 12 or more, then the email is classified as spam. Otherwise, it is classified as ham.

    Figure 2.1. Labeled data is data that comes with a tag, like a name, a type, or a number. Unlabeled data is data that comes with no tag.
    predict(email):
    if number of appearances of ‘sale’ is less than or equal to 3.5:
    classify as ham
    else:
    if number of appearances of ‘lottery’ is greater than 5.0:
    classify as spam
    else:
    if number of appearances of ‘sale’ is less than or equal to 8.0:
    classify as ham
    else: 
    Classify as spam
    Human-in-the-Loop Machine Learning

    This is an excerpt from Manning's book Human-in-the-Loop Machine Learning.

    Supervised learning models almost always get more accurate with more labelled data. Active Learning is the process of selecting which data needs to get a human label. Most research papers on Active Learning have focused on the number of training items. But the speed can be an even more important factor in many cases. Working in disaster response, I have often deployed Machine Learning models to filter and extract information from emerging disasters. Any delay in disaster response is potentially critical, so getting a usable model out quickly is more important than the number of labels that need to go into that model.

    def get_representative_cluster_samples(self, training_data, unlabeled_data,
                                    number=10, num_clusters=20, max_epochs=10, limit=10000):
            """Gets the most representative unlabeled items, compared to training data,
                                    across multiple clusters
           
            Keyword arguments:
                training_data -- data with a label, that the current model is trained on
                unlabeled_data -- data that does not yet have a label
                number -- number of items to sample
                limit -- sample from only this many items for faster sampling (-1 = no limit)
                num_clusters -- the number of clusters to create
                max_epochs -- maximum number of epochs to create clusters
          
            """
               
            if limit > 0:
                shuffle(training_data)
                training_data = training_data[:limit]
                shuffle(unlabeled_data)
                unlabeled_data = unlabeled_data[:limit]
               
            # Create clusters for training data
       
            training_clusters = CosineClusters(num_clusters)
            training_clusters.add_random_training_items(training_data)
           
            for i in range(0, max_epochs):    #A
                print("Epoch "+str(i))
                added = training_clusters.add_items_to_best_cluster(training_data)
                if added == 0:
                    break
       
            # Create clusters for unlabeled data
       
            unlabeled_clusters = CosineClusters(num_clusters)   
            unlabeled_clusters.add_random_training_items(training_data)
           
            for i in range(0, max_epochs):    #B
                print("Epoch "+str(i))
                added = unlabeled_clusters.add_items_to_best_cluster(unlabeled_data)
                if added == 0:
                    Break
     
    A: Create clusters within the existing training data
    B: Create clusters within the unlabeled data

    In fact, annotation can be one of the most transparent ways to contribute to an organization. If you have daily targets for the number of annotations, or can share how the accuracy goes up in your trained models, then it is easy to tie the annotation work to company goals. An annotator is much more likely to contribute to an increase in accuracy than a scientist experimenting with new algorithms, so this fact should be shared with your annotators!

    Figure 9.4: An example of how the accuracy of one annotator can be calculated by comparing the actual fraction of annotations for a given label to the number of annotations that was expected by an annotator. For our example data, this example would correspond to Cameron’s expectation that 65% of people would choose “Cyclist” for this task, compared to the 40% of people who actually chose it.
    Machine Learning Bookcamp

    This is an excerpt from Manning's book Machine Learning Bookcamp.

    With this set of features, we can encode any email as a feature vector: a sequence of numbers that contains all the feature values for a particular email.

    Figure 3.13 The global churn rate compared with churn rates among males and females. The numbers are quite close, which means that gender is not a very useful variable when predicting churn.
    for n in numbers:
        print(n)
    Ensemble Methods for Machine Learning

    This is an excerpt from Manning's book Ensemble Methods for Machine Learning.

    SVMs identify “support vectors”, a smaller working set of training examples that the model depends on. Counting the number of support vectors is not an effective way to measure of model complexity as small values of C restrict the model more, forcing it to use more support vectors in the final model.

    We visualize the performance of AdaBoost as the number of base estimators increases in the figure below. As we add more and more weak learners into the mix, the overall ensemble is increasingly boosted into a stronger, more complex and more nonlinear classifier.

    Figure 4.9 As the number of weak learners increases, the overall classifier is boosted into a strong model, which becomes increasingly nonlinear and is able to fit (and possibly overfit) the training data.
    Exploring Machine Learning Basics

    This is an excerpt from Manning's book Exploring Machine Learning Basics.

    Rule 6: Consider the number of the day, where Monday is 0, Tuesday is 1, Wednesday is 2, Thursday is 3, Friday is 4, Saturday is 5, and Sunday is 6. If we add the number of the day and the size of the email (in KB), and the result is 12 or more, then the email is classified as spam. Otherwise, it is classified as ham.

    Figure 2.1. Labeled data is data that comes with a tag, like a name, a type, or a number. Unlabeled data is data that comes with no tag.
    How Machine Learning Works

    This is an excerpt from Manning's book How Machine Learning Works.

    The number in the superscript of x is not a power, but the index of the example in the sample. We differentiate it form a power by putting it between parentheses. We reserve subscript numbers to distinguish different features.

    We can easily write a Python function that takes the data from our pandas DataFrame, add the values, and then divide that by the number of rows in the data to get the mean value, but pandas took care of that for us! By calling the mean() method on our DataFrame, we get the mean values for each column in the data.

    Where |R| is the number of points in the region R.

    import numpy as np
     
    def mse(y_true, y_pred):
        # Calculating the mean square error (MSE)
        return np.mean((y_true - y_pred) ** 2)
     
    class PrimitiveDecisionTreeRegressor:
       
        def __init__(self, stop_at=3):
            self.stop_at = stop_at
            self.tree = None
            
        def get_best_pivot(self, region_X, region_y):
           
            samples_count, features_count = region_X.shape
           
            # record each feature index with its possible values in a dictionary
            features_split_points = {}
            for i in range(features_count):
                features_split_points[i] = np.sort(region_X[:, i])
           
            # minimal mse is set to infinity at start
            minimal_mse = np.inf
            best_pivot = (None, None)
           
            # loop over all pairs of (feature_index, value)
            for i in range(features_count):
                for value in features_split_points[i]:
                   
                    # use boolean masks to get the samples in each subregion
                    left_region_mask = region_X[:, i] <= value
                    right_region_mask = ~left_region_mask
                   
                    # check the number of samples in each subregion
                    # if it's lower than the stopping criteria, we omit that split
                    left_region_X = region_X[left_region_mask]
                    right_region_X = region_X[right_region_mask]
                   
                    if left_region_X.shape[0] < self.stop_at or \
                        right_region_X.shape[0] < self.stop_at:
                        continue
                    
                    # get the y values in each region and calculate the split MSE
                    left_region_y = region_y[left_region_mask]
                    right_region_y = region_y[right_region_mask]
                   
                    left_mse = mse(left_region_y, np.mean(left_region_y))
                    right_mse = mse(right_region_y, np.mean(right_region_y))
                    total_mse = left_mse + right_mse
                   
                    # if the split MSE is lower than the prvious best
                    # we set the current split as the best one
                    if total_mse < minimal_mse:
                        minimal_mse = total_mse
                        best_pivot = (i, value)
                       
            return best_pivot
           
           
        def split(self, region_X, region_y, level=1):
           
            samples_count, _ = region_X.shape
           
            # if the samples count in the region to split meets
            # the stopping criteria, stop recursion and return a leaf node
            if samples_count <= self.stop_at:
                leaf_node = Node(is_leaf=True)
                leaf_node.attach_leaf_value(np.mean(region_y))
                return leaf_node
       
            # get the best pivot at this step and craete a decision node           
            split_feature, split_value = self.get_best_pivot(region_X, region_y)
            current_node = Node(pivot=(split_feature, split_value))
           
           
            print("{}Split on feature {} at {}".format(
                ''.join(['\t'] * level),
                split_feature,
                split_value)
            )
           
            left_region_mask = region_X[:, split_feature] <= split_value
            right_region_mask = ~left_region_mask
           
            # recursively split the left subregion and get its root node
            print("{}Left Region:".format(''.join(['\t'] * level)))
            left_region_X = region_X[left_region_mask]
            left_region_y = region_y[left_region_mask]
            left_child = self.split(left_region_X, left_region_y, level + 1)
           
            # recursively split the right subregion and get its root node
            print("{}Right Region:".format(''.join(['\t'] * level)))
            right_region_X = region_X[right_region_mask]
            right_region_y = region_y[right_region_mask]
            right_child = self.split(right_region_X, right_region_y, level + 1)
           
            # attach the left and right subregions to the decision node
            current_node.attach_children(left_child, right_child)
           
            return current_node
       
        def fit(self, X, y):
            self.tree = self.split(X, y)
           
        def predict(self, x):
            return self.tree.traverse(x)

    The law of large numbers states that as the number of trials increases, the average outcome of a random experiment will get closer and closer to the true expected value. Take for example on of the simplest random experiments ever, tossing a fair coin; one would expect that we’ll get heads 50% of the times we toss a fair coin. The law of large number says that if we tossed that for some number of times, and at each toss we counted the number of times heads appeared so far, we’ll find that this count approaches 50% of the trials as we toss the coin more and more. We can simulate that programmatically using numpy.random.choice and pass it an array that has two elements ‘H’ for heads and ‘T’ for tails. This function will simulate a random choice between ‘H’ and ‘T’ with equal probability, which is what we expect from a fair coin.

    np.random.seed(42)
     
    heads_count = 0
    averages = []
    for i in trials:
       
        sample = np.random.choice(['H', 'T'])
       
        heads_count += 1 if sample == 'H' else 0
        averages.append(heads_count / (i + 1))
     
    plt.plot(trials, averages) # plots the average count of H at each toss
    plt.axhline(0.5, linestyle='--', color='black') # plots the expected count of H
    Figure 7-12: The blue solid curve represents the empirical heads count fraction at each trial of the 10K trials, while the black dashed line represents the expected heads count fraction. The plot shows the law of large numbers in action as the number of trials increases, the empirical heads count fraction approaches the expected fraction.
    FIG 7-17

    In our little experiment above, we simulate tossing a fair coin for 10K times and at each trial we count the fraction of heads that we got so far, we’ll call that the empirical fraction. We then plot these fractions through time and compare it to the expected fraction, which is 50% (or 0.5 the times). This comparison, as shown in figure 7-12, demonstrates that the empirical fraction approaches the expected fraction as the number of trials increase. Or in other words, as the number of trials increase, it becomes less likely that the difference between the empirical fraction and the true fraction to be large. This last sentence is exactly what the mathematical formula of the law of large number says.

    In a more general setting, the law of large number says that as the number of samples m increases, it’s less likely that the difference between the empirical average (or the empirical mean) and the expected value of a random variable to be large. To write that last sentence mathematically for some random variable , we define an arbitrary small positive value that we denote with the symbol epsilon  and then we talk about the probability of the absolute difference  being greater than or equal that small value . So the law of large number is finally written as:

    eq7-9

    This is simply read like: as the number of samples m becomes larger and approaches infinity, the gap between the empirical mean and the expected value being greater than some small value  will probably be zero.

    Machine Learning with R, the tidyverse, and mlr

    This is an excerpt from Manning's book Machine Learning with R, the tidyverse, and mlr.

    A vector is a set of numbers that encodes both magnitude and direction. Imagine a coordinate system with an x-axis and a y-axis, as shown in figure A.2. If we pick a point on the coordinate system, that point will have a value for each axis: let’s say x = 3 and y = 5. We can represent this point as the vector (3,5). The vector encodes magnitude, because we can calculate the distance between the point defined by this vector and the origin of the coordinate system (0,0). The vector also encodes direction, because if we draw a line connecting the origin (0,0) to this point (3,5), we can calculate the angle between this line and the axes of the coordinate space. Figure A.2 is an example of a two-dimensional vector, but vectors can have as many dimensions as we like.

    Listing 9.9. Tuning the number of predictors to retain
    lmParamSpace <- makeParamSet(
      makeIntegerParam("fw.abs", lower = 1, upper = 12)
    )
    
    gridSearch <- makeTuneControlGrid()
    
    kFold <- makeResampleDesc("CV", iters = 10)
    
    tunedFeats <- tuneParams(filterWrapper, task = ozoneTask, resampling = kFold,
                            par.set = lmParamSpace, control = gridSearch)
    
    tunedFeats
    
    Tune result:
    Op. pars: fw.abs=10
    mse.test.mean=20.8834

    The intuition here is that if we maintain the same diameter of our clusters but move the closest pair apart, the Dunn index will get larger. Conversely, if we maintain the same distance between cluster centroids but shrink the diameter of the clusters (by making the clusters denser), the Dunn index will also increase. As such, the number of clusters resulting in the largest Dunn index is the one that results in the largest minimum distance between clusters and the smallest maximum distance between cases within a cluster.

    The pseudo F statistic is a ratio of the between-cluster sum of squares to the within-cluster sum of squares (see figure 16.6). The between-cluster sum of squares is the squared difference between each cluster centroid and the grand centroid (the centroid of the data as if it was all in one big cluster), weighted by the number of cases in that cluster, added up across each cluster. This is another way of measuring how separated the clusters are from each other (the farther the cluster centroids are from each other, the smaller the between sum of squares will be). The within-cluster sum of squares is the squared difference between each case and its cluster’s centroid, added up across each cluster. This is another way of measuring the variance or dispersion within each cluster (the denser each cluster is, the smaller the within-cluster sum of squares will be).

    Figure 16.6. The pseudo F statistic is the ratio of the between-cluster sum of squares (right-side plot) to the within-cluster sum of squares (left-side plot). The grand centroid is shown as a square in the right-side plot.

    Because the pseudo F statistic is also a ratio, if we maintain the same cluster variance but move the clusters farther apart, the pseudo F statistic will increase. Conversely, if we maintain the same separation between the cluster centroids but make the clusters more spread out, the pseudo F statistic will decrease. As such, the number of clusters that results in the largest pseudo F statistic is, in theory, the one that maximizes the separation of the clusters.

    Machine Learning for Business: Using Amazon SageMaker and Jupyter

    This is an excerpt from Manning's book Machine Learning for Business: Using Amazon SageMaker and Jupyter.

    Productivity is measured at a country level by dividing the annual Gross Domestic Product (GDP) by the number of hours worked in a year. The GDP per hour worked in the UK and the US is currently just over US$100. In 1970, it was between US$45 and US$50. But the GDP per hour worked by the top 5% of firms (the frontier firms) is over US$700 and rising.

    Kiara works for a retail chain that has 48 locations around the country. She is an engineer, and every month her boss asks her how much energy they will consume in the next month. Kiara follows the procedure taught to her by the previous engineer in her role: she looks at how much energy they consumed in the same month last year, weights it by the number of locations they have gained or lost, and provides that number to her boss. Her boss sends this estimate to the facilities management teams to help plan their activities and then to Finance to forecast expenditure. The problem is that Kiara’s estimates are always wrong—sometimes by a lot.

    Listing 6.12. Viewing the number of rows and columns
    print(f'Number of rows in dataset: {df.shape[0]}')
    print(f'Number of columns in dataset: {df.shape[1]}')
  • Time-series data consists of a number of observations at particular intervals. You can visualize time-series data as line charts.
  • Figure 7.4. Number of staff rostered during a month with a shutdown
    Machine Learning with TensorFlow

    This is an excerpt from Manning's book Machine Learning with TensorFlow.

    When shopping for cars, you might find comparing mileage to be more lucrative than comparing something less relevant to your interest, such as weight. The number of features to track also must be just right: not too few, or you’ll lose information you care about, and not too many, or they’ll be unwieldy and time consuming to keep track of. This tremendous effort to select both the number of measurements and which measurements to compare is called feature engineering. Depending on which features you examine, the performance of your system can fluctuate dramatically. Selecting the right features to track can make up for a weak learning algorithm.

    The beauty of the CNN is that the number of parameters is independent of the size of the original image. You can run the same CNN on a 300 × 300 image, and the number of parameters won’t change in the convolution layer!

    A quick and dirty heuristic you can use to compare the flexibility of two machine-learning models is to count the number of parameters to be learned. As shown in figure 9.1, a fully connected neural network that takes in a 256 × 256 image and maps it to a layer of 10 neurons will have 256 × 256 × 10 = 655,360 parameters! Compare that to a model with perhaps only 5 parameters. It’s likely that the fully connected neural network can represent more-complex data than the model with 5 parameters.

    Figure 9.1. In a fully connected network, each pixel of an image is treated as an input. For a grayscale image of size 256 × 256, that’s 256 × 256 neurons! Connecting each neuron to 10 outputs yields 256 × 256 × 10 = 655,360 weights.

    The next section introduces convolutional neural networks, which are a clever way to reduce the number of parameters. Instead of dealing with a fully connected network, the CNN approach reuses the same parameter multiple times.

    Real-World Machine Learning

    This is an excerpt from Manning's book Real-World Machine Learning.

    For the first couple of weeks, the two of you stay up with demand. Yet the number of applications continues to grow, doubling within a month to 1,000 per week. To keep up with this increased demand, you now must hire two more analysts. Projecting forward, you determine that this pattern of hiring isn’t sustainable: all of your increased revenue from new loan applicants is going directly to your new hires instead of to more-critical areas such as your microlending fund. Hiring more analysts as demand increases hinders the growth of your business. Further, you find that the hiring process is lengthy and expensive, sapping your business of more of its revenue. Finally, each new hire is less experienced and slower at processing applications than the last, and the added stress of managing a team of individuals is wearing on you.

    The tf can be calculated in different ways, but the simplest is to use the number of times a word occurs in a particular document. It’s also common to use other versions of the tf factor, such as binary (1 if the word is in a document, and 0 otherwise) and logarithmic (1 + log[tf]).

    The inverse document frequency is calculated as the logarithm of the total number of documents, divided by the number of documents that contain the term, so that relatively uncommon words attain higher values. In its simplest form, the tf-idf equation looks like this:

    Tf-idf can be powerful for generating good ML features from any corpus of text. It can also be useful in other areas, such as search. Because you’re generating a vector of numbers for any document, you can also find “distances” between documents, as distances between their tf-idf vector representations. If the user search query is a document, you can find the distances between any other documents in your dataset in this way, and hence return a ranked list of documents to the user based on the query. Listing 7.1 in the next section shows how to use the scikit-learn Python library to generate tf-idf vectors from documents, along with a more advanced technique called latent semantic indexing.

    Listing 7.2. Latent Dirichlet analysis in Python using Gensim
    import gensim.models.ldamodel.LdaModel #1 def lda_model(docs): #2 return LdaModel(docs, num_topics=20) def lda_vector(lda_model, doc): #3 return lda_model[doc] #1 - Must install Gensim first, by running “pip install gensim” #2 - Builds LDA model, setting the number of topics to extract #3 - Generates features for a new document

    The number of topics used in the LDA model is a parameter that needs to be tuned to the data and problem at hand. We encourage you to define your performance metric and use the techniques in chapter 4 to optimize your model. It’s also worth noting that the LDA in Gensim can be updated on the fly with new documents if new training data is coming in continuously. We encourage you to check out the many other interesting natural-language and topic-modeling algorithms in Gensim. In chapter 10, you’ll use some of these advanced text-feature-extraction techniques to solve a real-world machine-learning problem. The next section introduces a completely different method for text-feature extraction: expanding the content of the text.

    Algorithms of the Intelligent Web, Second Edition

    This is an excerpt from Manning's book Algorithms of the Intelligent Web, Second Edition.

    But we’re getting ahead of ourselves. In this chapter, we’ll provide several examples of the application of intelligent algorithms that you should find immediately recognizable. We’ll talk more about what intelligent algorithms can’t do, before providing you with a taxonomy of the field that can be used to hang your newly learned concepts on. Finally, we’ll present you with a number of methods to evaluate intelligent algorithms and impart to you some useful things to know.

    Listing 5.1. Determining how balanced the data is
    wc -l train_vw_file #1 > 32090601 train_vw_file grep –c '^-1' train_vw_file #2 > 23869264 grep –c '^1' train_vw_file #3 > 8221337 #1 - Uses word count (wc) to determine the number of lines in the data file #2 - Counts only those lines starting with a -1 (negative example) #3 - Counts only those lines starting with a 1 (positive example)

    It might be useful for you to think about the factors that will impact the size of z. Obviously, if we draw two conversion rates at a given point in time from an experimental set and a control set, a larger difference in these will lead to a larger z score, and therefore more evidence that they’re drawn from different populations with different means. But the number of samples is also important. As you’ve seen, a larger number of samples will lead to an overall smaller standard error. This captures the fact that our estimate of conversion rate is more accurate the longer we run the experiment. In the following section, we’ll provide an illustration of this and a worked example of A/B testing in Python using this methodology.

    As before, we create multiple runs through the experiment, each time reinitializing the learned parameters. The total cumulative expected regret is calculated at each step, and the average is calculated by dividing this array by an array containing the number of runs. This yields the output given in figure 7.9.

    Figure 7.9. Average cumulative expected regret at each step, over 100 iterations. Note that the gradient decreases as the number of steps increases. This is because the Bayesian bandit makes comparative better choices as the experiment continues. Consequently, it’s less likely to incur additional regret.

    You can see that as the number of steps in the experiment increases, the rate at which regret is accumulated decreases. This is because the Bayesian bandit is, more often, making better decisions on average, at later stages in an individual run. Although the curve in figure 7.9 hasn’t converged within 1,000 steps (that is, the gradient hasn’t dropped to zero), it does look like the Bayesian bandit expects to lose somewhere in the order of 10 payouts when compared to a totally optimal strategy. If we consider that the optimal strategy pays out around 1,000 × 0.8 = 800 times, this isn’t bad at all.

  • Scale of probability— If we repeat this experiment, replacing the probabilities with those divided by 10 (probabilities of 1 become 0.1, 0.9 becomes 0.09, and so on), then we see an interesting trend. The ordering of the cumulative expected regret inverts (see figure 7.11)! But why is this? By reducing the magnitude of the probabilities, positive events are much less likely to occur. This means several things. First, the number of steps required for our beliefs to converge is larger, because we must pull the arms more often to obtain any information about the bandit. Second, this has the knock-on effect that the overall regret will be higher than when working with bandits with higher probabilities. The reason for the inversion of the ordering is that this is such an early stage of the regret curve. Consider figure 7.11 against the first 30 iterations of figure 7.10. Put another way, it takes 1,000 iterations in our second experiment to learn the equivalent of the first 30 iterations of our first!
  • Number of bandits— Let’s repeat our experiment by increasing the number of bandits from 1 to 10. Each will be evenly balanced in the probability space. So, for example, 1 bandit always pays out, 2 bandits pay out at rates of 1 and 0.5, 3 bandits at rates of [1,0.66,0.33], and so on. Figure 7.12 shows the equivalent output. What you see here is a tendency for an increased regret and a slower convergence, but this difference in speed isn’t as marked as with the first two experiments. The speed of convergence seems to be dominated by the overall probabilities of payout and the proximity of the probability distributions to each other, not as much by the number of other bandits within the experiment.
  • Figure 7.12. Cumulative expected regret for 10 experiments, each with an increasing number of bandits. As we increase the number of bandits, their probabilities of payout are spread equally through the space, excluding the zero-probability bandit.
    Introducing Data Science: Big data, machine learning, and more, using Python tools

    This is an excerpt from Manning's book Introducing Data Science: Big data, machine learning, and more, using Python tools.

    Data science and big data are used almost everywhere in both commercial and noncommercial settings. The number of use cases is vast, and the examples we’ll provide throughout this book only scratch the surface of the possibilities.

    Although data is considered an asset more valuable than oil by certain companies, more and more governments and organizations share their data for free with the world. This data can be of excellent quality; it depends on the institution that creates and manages it. The information they share covers a broad range of topics such as the number of accidents or amount of drug abuse in a certain region and its demographics. This data is helpful when you want to enrich proprietary data but also convenient when training your data science skills at home. Table 2.1 shows only a small selection from the growing number of open-data providers.

    Reducing the number of variables

    Sometimes you have too many variables and need to reduce the number because they don’t add new information to the model. Having too many variables in your model makes the model difficult to handle, and certain techniques don’t perform well when you overload them with too many input variables. For instance, all the techniques based on a Euclidean distance perform well only up to 10 variables.

    Data scientists use special methods to reduce the number of variables but retain the maximum amount of data. We’ll discuss several of these methods in chapter 3. Figure 2.12 shows how reducing the number of variables makes it easier to understand the key values. It also shows how two variables account for 50.6% of the variation within the data set (component1 = 27.8% + component2 = 22.8%). These variables, called “component1” and “component2,” are both combinations of the original variables. They’re the principal components of the underlying data structure. If it isn’t all that clear at this point, don’t worry, principal components analysis (PCA) will be explained more thoroughly in chapter 3. What you can also see is the presence of a third (unknown) variable that splits the group of observations into two.

    Figure 2.12. Variable reduction allows you to reduce the number of variables while maintaining as much information as possible.
    sqlContext.sql("drop table if exists LoansByTitle")
    sql = '''create table LoansByTitle stored as parquet as select title,
         count(1) as number from loans group by title order by number desc'''
    sqlContext.sql(sql)
    
    sqlContext.sql('drop table if exists raw')
    sql = '''create table raw stored as parquet as select title,
         emp_title,grade,home_ownership,int_rate,recoveries,collection_recovery_f
         ee,loan_amnt,term from loans'''
    sqlContext.sql(sql)
    Mahout in Action

    This is an excerpt from Manning's book Mahout in Action.

    Mahout incubates a number of techniques and algorithms, many still in development or in an experimental phase (https://cwiki.apache.org/confluence/display/MAHOUT/Algorithms). At this early stage in the project’s life, three core themes are evident: recommender engines (collaborative filtering), clustering, and classification. This is by no means all that exists within Mahout, but they are the most prominent and mature themes at the time of writing. These, therefore, are the focus of this book.

    The Pearson correlation is a number between –1 and 1 that measures the tendency of two series of numbers, paired up one-to-one, to move together. That is to say, it measures how likely a number in one series is to be relatively large when the corresponding number in the other series is high, and vice versa. It measures the tendency of the numbers to move together proportionally, such that there’s a roughly linear relationship between the values in one series and the other. When this tendency is high, the correlation is close to 1. When there appears to be little relationship at all, the value is near 0. When there appears to be an opposing relationship—one series’ numbers are high exactly when the other series’ numbers are low—the value is near –1.

    The third line shows how it’s based on item-item similarities, not user-user similarities as before. The algorithms are similar, but not entirely symmetric. They do have notably different properties. For instance, the running time of an item-based recommender scales up as the number of items increases, whereas a user-based recommender’s running time goes up as the number of users increases.

    This suggests one reason that you might choose an item-based recommender: if the number of items is relatively low compared to the number of users, the performance advantage could be significant.

    Figure 9.13. Dirichlet clustering: the models are made to fit the given data set as best they can to describe it. The right model will fit the data better and indicates the number of clusters in the data set that correlates with the model.
    Collective Intelligence in Action

    This is an excerpt from Manning's book Collective Intelligence in Action.

    Figure 1.7. Screen shot from Digg.com showing news items with the number of diggs for each

    In his book The Hundredth Monkey,[1] Ken Keyes recounts an interesting story about how change is propagated in groups. In 1952, on the isolated Japanese island of Koshima, scientists observed a group of monkeys. They offered them sweet potatoes; the monkeys liked the sweet potatoes but found the taste of dirt and sand on the potatoes unpleasant. One day, an 18-month-old monkey named Imo found a solution to the problem by washing the potato in a nearby stream of water. She taught this trick to her mother. Her playmates also learned the trick and taught it to their mothers. Initially, only adults who imitated their children learned the new trick, while the others continued eating the old way. In the autumn of 1958, a number of monkeys were washing their potatoes before eating. The exact number is unknown, but let’s say that out of 1,000, there were 99 monkeys who washed their potatoes before eating. Early one sunny morning, a 100th monkey decided to wash his potato. Then, incredibly, by evening all monkeys were washing their potatoes. The 100th monkey was that tipping point that caused others to change their habits for the better. Soon it was observed that monkeys on other islands were also washing their potatoes before eating them.

    When the number of clusters is set to -1, EM uses cross validation to select the number of clusters to be used. The algorithm splits the dataset into 10 instances. It assigns the number of clusters to be 1 and then performs tenfold cross validation. The log likelihood is computed for each of the 10 runs and averaged. If the log likelihood increases, then the number of clusters is increased by one and the whole process continues. The Clusterer instance clusters the dataset using the following code:

  • Clusterer: the main interface for discovering clusters. It consists of a number of clusters represented by TextCluster.
  • TextCluster: represents a cluster. Each cluster has an associated TagMagnitudeVector for the center of the cluster and has a number of TextDataItem instances.
  • TextDataItem: represents each text instance. A dataset consists of a number of TextDataItem instances and is created by the DataSetCreator.