Trending December 2023 # Working Of Kmeans Algorithm In Opencv? # Suggested January 2024 # Top 19 Popular

You are reading the article Working Of Kmeans Algorithm In Opencv? updated in December 2023 on the website Moimoishop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Working Of Kmeans Algorithm In Opencv?

Introduction to OpenCV kmeans

Web development, programming languages, Software testing & others

Syntax:

cv.kmeans(samples, nclusters(k), criteria, attempts, flags)

where samples are the set of data that is to be grouped into clusters,

nclusters(k) is the number of clusters into which the given set of data must be grouped,

criteria are the criteria based on which the algorithm iteration terminates,

attempts specifies the number of times the algorithm is executed with different centroids and

flags specify how the centroids are chosen.

Working of kmeans algorithm in OpenCV?

Working of kmeans algorithm in OpenCV is as follows:

The kmeans algorithm starts by randomly choosing the data points as Centroids C1, C2, and so on.

Then it calculates the distance between each data point in the data set to the centroids.

Then all the data points closer to each centroid are grouped by labeling them with 0, 1, and so on.

Then the average of all the data points labeled with 0, 1, and so on are calculated separately and the result is made as the new centroid C1, C2, and so on.

The same procedure is repeated until the centroids are converged to a fixed point.

The sum of the distances between each data point and their corresponding centroids must be minimum.

The set of data to be clustered into different groups using kmeans algorithm must be of np.float32 data type.

The criterion for termination of iteration is a tuple of three parameters namely type, max_iter, and epsilon.

The parameter type specified the type of criteria for termination which has three flags.

The three flags for type of termination criteria are cv.TERM_CRITERIA_EPS, cv.TERM_CRITERIA_MAX_ITER and cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER.

The parameter type max_iter specifies the maximum number of iterations.

The parameter type epsilon specifies the accuracy that is required.

The parameter attempts returns the compactness as the output.

Two flags are used to choose the centroids initially, they are KMEANS_PP_CENTERSand cv.KMEANS_RANDOM_CENTERS.

Examples

Let us discuss examples of OpenCV kmeans.

Example #1

OpenCV program in python to demonstrate the application of kmeans algorithm by creating a data set consisting of a single feature and then apply kmeans() function to group the created data set into two clusters by specifying the type of termination criteria, maximum number of iterations, epsilon, attempts and flags and plot the resulting clusters along with their corresponding centroids as the output on the screen:

#importing the modules numpy, cv2 and pyplot import numpy as np import cv2 as cv from matplotlib import pyplot as plt #creating a two dimensional array consisting of 50 elements in the range 0-255 first = np.random.randint(20, 100, 25) second = np.random.randint(170, 255, 25) #stacking the two arrays into a single array resarray = np.hstack((first, second)) #reshaping the resulting array to a column vector resarray = resarray.reshape((50, 1)) #converting the type of the resulting array to np.float32 resarray = np.float32(resarray) #defining the termination criteria with type, max_iter and epsilon criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 20, 2.0) # specifying the flag to choose the centroids flags = cv.KMEANS_RANDOM_CENTERS #applying kmeans function to cluster the given set of date into two clusters compactness, labels, centers = cv.kmeans(resarray, 2, None, criteria, 20, flags) #plotting the graph of two clusters against labels with one cluster in black color, another cluster in yellow color and centroids in red color cluster1 = resarray[labels==0] cluster2 = resarray[labels==1] plt.hist(cluster1, 256, [0, 256], color='black') plt.hist(cluster2, 256, [0, 256], color='yellow') plt.hist(centers, 32, [0, 256], color='red') plt.show()

The output of the above program is shown in the snapshot below:

In the above program, we are creating a two-dimensional array and converting it into a column vector and then applying kmeans() function on the created data set to group the data set into two clusters, and the resulting two clusters along with their corresponding centroids is plotted in a graph and displayed as the output on the screen.

Example #2

OpenCV program in python to demonstrate the application of kmeans algorithm by creating a data set consisting of a single feature and then apply kmeans() function to group the created data set into three clusters by specifying the type of termination criteria, maximum number of iterations, epsilon, attempts and flags and plot the resulting clusters along with their corresponding centroids as the output on the screen:

#importing the modules numpy, cv2 and pyplot import numpy as np import cv2 as cv from matplotlib import pyplot as plt #creating a two dimensional array consisting of 50 elements in the range 0-255 first = np.random.randint(0, 100, 30) second = np.random.randint(100, 255, 30) #stacking the two arrays into a single array resarray = np.hstack((first, second)) #reshaping the resulting array to a column vector resarray = resarray.reshape((60, 1)) #converting the type of the resulting array to np.float32 resarray = np.float32(resarray) #defining the termination criteria with type, max_iter and epsilon criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 20, 2.0) # specifying the flag to choose the centroids flags = cv.KMEANS_RANDOM_CENTERS #applying kmeans function to cluster the given set of date into two clusters compactness, labels, centers = cv.kmeans(resarray, 3, None, criteria, 20, flags) #plotting the graph of three clusters against labels with one cluster in black color, another cluster in yellow color and the last cluster in green color and centroids in red color cluster1 = resarray[labels==0] cluster2 = resarray[labels==1] cluster3 = resarray[labels==2] plt.hist(cluster1, 256, [0, 256], color='black') plt.hist(cluster2, 256, [0, 256], color='yellow') plt.hist(cluster3, 256, [0, 256], color='green') plt.hist(centers, 32, [0, 256], color='red') plt.show()

The output of the above program is shown in the snapshot below:

In the above program, we are creating a two-dimensional array and converting it into a column vector and then applying kmeans() function on the created data set to group the data set into three clusters, and the resulting three clusters along with their corresponding centroids is plotted in a graph and displayed as the output on the screen.

Conclusion

In this article, we have learnt the concept of kmeans algorithm through definition, syntax, and working of kmeans algorithm with corresponding programming examples and their outputs to demonstrate them.

Recommended Articles

We hope that this EDUCBA information on “OpenCV kmeans” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading Working Of Kmeans Algorithm In Opencv?

Learn The Working Of Unhide In Sketchup

Introduction to SketchUp Unhide How Unhide works in SketchUp?

You can unhide objects in this software by using menus of the menu bar and some other options so let me tell you how you can do this during your work.

Start Your Free Design Course

3D animation, modelling, simulation, game development & others

I have downloaded this chair’s model from the 3D warehouse of SketchUp to explain this topic. You can learn and practices this on your own designed model.

Once I will choose this option, it will hide our selected chair. I will do the same with some other chairs.

And you can see it will unhide the entire hidden object, but this option (Last) is used to unhide the last unhide object. In the current case, it unhides all hidden objects because we have been hiding all chairs one by one in sequence.

Now let us understand this option in another way through which it will only unhide the last hidden object. I will hide this selected chair again and then create an object like this by using push/pull and rectangle tools.

I will add one block to this object also.

It will unhide only the last hidden chair. So I think you got it that if we hide any component then do other design work, then it will only unhide the last hidden object.

I will hide this drawn object too in the same way.

Now once again, go to Unhide option of the Edit menu and this time choose the All sub-option of Unhide option.

And it will show you a wireframe view of all hidden objects of your working model like this. I have been hidden these chairs only, so it is showing them only.

Now I will select this first chair which is in wireframe view, and choose Selected sub-option from the Unhide option.

And it will unhide only this chair. So by this way, you can unhide only your desired object or component during working on any project.

Here in the dialog box of Model info, choose the Components option from the shown list.

If you select other components, then the first select object will become disappear like this.

Here in the dialog box of Preferences, choose the Shortcuts option from the shown list and select the ‘Hide rest of object’ option in the list of Functions tab. Then go to Add Shortcut box and assign your desired key with a combination of the Ctrl key of the keyboard. Once you assign a key to it, if that combination of keys is already assigned to another command, then it will show you a message that it is already assigned. So choose that one that is not allotted to another command.

Conclusion

These were some important aspects of Unhide feature of SketchUp, and you can use it for having smooth working ability during creating a 3D model. You can go with any of the above-discussed ways according to your work requirement. You can also assign a shortcut key to ‘hide other objects’ as per your choice for speeding up your working skill in SketchUp.

Recommended Articles

This is a guide to SketchUp Unhide. Here we discuss the working of Unhide in SketchUp by using few options through which you can do the process of unhiding objects. You may also have a look at the following articles to learn more –

Working And Examples Of If Statement In React

Introduction to React If

For any coder or a Developer, applying If statements is one of the most basic skills they need. If statements are used to make behavioral changes in the product. For example, If a person’s age is above 18, he can drive a vehicle else; he is not eligible for driving. It also supports If statements. It comes under conditional rendering and is used just the way it is used in JavaScript. If a statement is used to match the condition, let the User Interface reaction be the basis of the user’s action. This article has covered some examples to help you understand how the If statement can be used to React to fulfill our requirements.

Start Your Free Software Development Course

Syntax

Working of If statement in React

As we can see in the above syntax of the If statement in React, Here, the age which the user provides is matched against the driving age, and if the user’s age fulfills the condition, then there is a success message; otherwise, the user is not eligible for driving. This was a basic example to understand the working of the If statement in React.

Examples of React If

Different examples are mentioned below:

Example #1 – Basic Example of React If

index.js (inside component folder)

import React from "react"; return ( ); }; return ( ); };

index.js (main file)

import React from "react"; import ReactDOM from "react-dom"; import { Button , Form } from "./components"; import "./styles.css"; class App extends React.Component { constructor(props) { super(props); this.state = { showForm: false }; } this.setState({ showForm: !this.state.showForm }); }; render() { let RenderedComponent; if (this.state.showForm) { } else { } } } const rootElement = document.getElementById("root");

chúng tôi

.App { font-family: times; text-align: center; }

Output:

Examples #2 – React If in a Form

Below we have made a registration form, where one can choose training according to one’s preference. The “If” statement is used so that no detail gets left unfilled. In the example below, we have used if statement in values.firstName, values.reception, values.street and values.pickupTime inside chúng tôi file.

chúng tôi

import React from 'react' import { render } from 'react-dom' import Styles from './Styles' import { Form , Field } from 'react-final-form' import pickupTimes from './pickupTimes' const sleep = resolve, ms) ) await sleep(300) window.alert(JSON.stringify(values, 0, 2)) } const Error = ( { name } { ( { meta: { error, touched } } } ) { ( { input: { value } } } ) Link to Our Website Please fill the below form so that we can customize the training and newsletter according to your Choices. <Form onSubmit={onSubmit} initialValues={{ EmploymentStatus: true, YourAdvisor: 'Rahul' }} const errors = {} if (!values.firstName) { errors.firstName = 'Required' } if (!values.reception) { errors.reception = 'Required' } if (values.reception === 'delivery') { if (!values.street) { errors.street = 'Required' } } else if (values.reception === 'pickup') { if (!values.pickupTime) { errors.pickupTime = 'Required' } } return errors }} > {({ handleSubmit , form , submitting , pristine <Field name="firstName" component="input" type="text" placeholder="Full Name" <Field name="reception" component="input" type="radio" value="liveinteractive" Live Interactive Training <Field name="reception" component="input" type="radio" value="selfpaced" Self Paced Training <Field name="street" component="input" type="text" placeholder="Your Address" {time} ))} <Field name="message" component="textarea" placeholder="Your Name" )} )

chúng tôi

import styled , { css } from 'styled-components' white-space: nowrap; display: inline-block; border-radius: 4px; padding: 4px 14px; font-size: 15px; color: #030303; &:visited { color: #baf573; } background-image: linear-gradient(${light}, ${dark}); border: 0.5px solid ${dark}; &:hover { background-image: linear-gradient(${light}, ${dark}); &[disabled] { background-image: linear-gradient(${light}, ${dark}); } } &:visited { color: #171716; } &[disabled] { opacity: 0.5; cursor: not-allowed; } const btnDefault = css` ${btn('#b5f7e3', '#e2f7b5')} color: #b7b8b4; const btnPrimary = btn('#d07dfa', '#7dd7fa') const btnDanger = btn('#eb6399', '#fcf586') export default styled.div` font-family: 'Times New Roman' , Times , serif; h1 { text-align: center; color: #cc235b; } h2 { text-align: center; color: #2623cc; } text-align: center; } a { display: block; text-align: center; color: #c780f2; margin-bottom: 9px; } p { max-width: 501px; margin: 9px auto; display: inline; } } .loading { font-size: 3em; font-weight: bold; text-align: center; margin: 49px; } form, div.form { text-align: left; max-width: 501px; margin: 9px auto; border: 0.5px solid #f58867; padding: 19px; box-shadow: 1px 1px 4px #f58867; border-radius: 2px; position: relative; display: flex; flex-flow: row nowrap; line-height: 1em; margin: 4px; position: relative; color: #ed4a96; width: 111px; min-width: 59px; font-size: 1.15em; line-height: 31px; } flex: 2; padding: 4px 6px; font-size: 1.15em; margin-left: 14px; border: 0.5px solid #7cf2e6; border-radius: 0.5px; } margin-top: 7px; } margin-left: 15px; margin-left: 0; display: block; margin-right: 2px; } } &.downshift { margin-left: 0; padding-left: 14px; flex: 1; width: 99%; padding: 5px 4px; font-size: 1.15em; margin-left: 0; border: 1.15px solid #d7f587; border-radius: 2px; } } } line-height: 29px; margin-left: 9px; color: #f52c2c; font-weight: bold; } ${btnDanger}; } } display: flex; flex-flow: row nowrap; justify-content: center; margin-top: 14px; } .error { display: flex; font-weight: bold; color: #f52c2c; flex-flow: row nowrap; justify-content: center; } pre { position: relative; border: 1.15px solid #e0faa5; background: #e6ff99; box-shadow: inset 2px 2px 2px #30302f; padding: 21px; } .submitting { display: block; position: absolute; top: -2px; left: -4px; right: -4px; padding: 0; text-align: center; background: #41423e; color: #f4f5f2; z-index: 11; font-weight: bold; font-size: 0.9em; } .saving { font-size: 0.9em; font-weight: bold; color: #516bed; margin: 9px 0 0 6px; } } button { margin: 0 9px; &[type='submit'] { ${btnPrimary}; } &[type='button'] { ${btnDefault}; } } .downshift-options { border: 2px solid #a0f2d8; box-shadow: 2px 2px 3px #1a1b1c; padding: 3px 5px; } } `

chúng tôi

const now = new Date(); let hours = now.getHours(); const times = []; if (now.getMinutes() < 30) { times.push(`${++hours}:30`); } else { hours++; } while (times.length < 6) { times.push(`${hours}:00`); times.push(`${hours}:30`); hours = ( hours + 1 ) % 24; } export default times;

Conclusion

Based on the above article, we understood the working of the If statement in React. Then, we went through a couple of examples to understand how an If statement can be used in different situations to change the behavior of the app according to the user’s action.

Recommended Articles

This is a guide to React If. Here we discuss the introduction, syntax, and working of the If statement in React along with examples and code implementation. You may also have a look at the following articles to learn more –

Working Of Localtime() Function In Perl With Examples

Introduction to Perl localtime

Web development, programming languages, Software testing & others

Working of localtime() Function in Perl with Examples

In this article, we will see the Perl time function known as localtime(), which is defined as a function for returning the time elements related to the date and time of the system or program. In Perl, date and time codes usually need a Perl module known as the DateTime module, which contains various combinations of representation of date and time where; this module uses a New Style calendar, which is known as a geographic calendar.

In Perl, to display date and time that has analyzed time of the current time zone which is done by converting the given expression of time into a set of time elements which is an array of time elements and contains at least 9 element in this array which includes the time and date of the current time zone such as second, minute, hour, day, month, year, day of the week, day of the year, isdst.

Now let us see syntax and examples of localtime() function:

Syntax:

Use DateTime; localtime();

In this, if there is no argument passed, then the localtime() function returns the current date and time of the timezone.

or with expression : locatime expr;

In this, we can write expr anything which can display result related to time elements only.

In the above syntax, both can be used where the first one displays the set of time elements having 9 different elements defining the time of time zone. Then the second syntax can display only those time elements which are specified as expression (expr) in the syntax as seen in the above syntax section.

Example #1 #!/usr/local/bin/perl use DateTime; print "Demonstration of localtime() function in Perl"; print "n"; print "n"; print "The use of localtime() function without any arguments "; print "n"; $sys_dt = localtime(); print "The date and time of the system of the timezone which is used is :"; print "n"; print $sys_dt; print "n"; print "The localtime() function to display particular format of date and time"; print "n"; @mon_name = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); @day_name = qw(Sun Mon Tue Wed Thu Fri Sat Sun); ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); print "The current day name and month name is: "; print "n"; print "$mday $mon_name[$mon] "; print "$day_name[$wday] ";

Output:

In the above program, we can see we have first imported a Perl module for date and time as “use DateTime” so that we can use locatime() inbuilt function of Perl. In the above code, we are declaring a variable that stores the current date and time of the system where we are assigning this variable to store the value of the locatime() function and is displayed using the print command. In this, we have not passed any argument to the function, so it will just print the current day date and the current time in an hour, minutes and seconds along with the current year.

Then we are trying to use the localtime() function to display a particular date and time format, which we specify in print command where in the code we are printing only the current date with day and current month using localtime() function. Therefore we can use this function in both ways. We have written the month and day name in which format we want to display, and these are stored in the variables “mon_name” and “day_name” so that we can display in the same name which is defined here; we can also use full name to display here. The output can be seen in the above screenshot, which displays the system’s current date and time.

Example #2

Code:

#!/usr/local/bin/perl use DateTime; print "Demonstration of localtime() fucntion with argument in Perl"; print "n"; print "n"; $cur_dt = localtime(); print "The current date and time is as follows: "; print "n"; print $cur_dt; print "The elapsed time and date can be represented using time() function"; print "n"; $epoc = time(); $epoc = $epoc - 24 * 60 * 60; print "The elapsed time in seconds to display  yesterday's date and time is "; print "n"; print $epoc; print "n"; $cur_dt = localtime($epoc); print "The epoc passed as argument for displayng yesterday's date and time:"; print "n"; print $cur_dt;

Output:

In the above code, first, we import the “use DateTime” module for using the localtime() function. In this code, first, we have declared a variable to display the current date and time, which displays the current date and time of the system and then we are using another variable, “$epoc,” in which we are storing the number of seconds that are elapsed until the current day and time using time() function. Therefore we can see we have then passed this $epoc to the localtime() function, which displays yesterday’s date and time. The output for this code can be seen in the above screenshot.

Conclusion

In this article, we conclude that the localtime() function is a time function used to display the date and time of the time zone the system is using. This function returns the set or array of time elements which has 9 different elements of date and time such as hour, minutes, seconds, etc. In the article, we saw a simple example of using localtime() without argument and to display the particular date and time elements and also we saw another example where we are passing the elapsed time to display the elapsed date that is passed as an argument to the localtime() function.

Recommended Articles

This is a guide to Perl localtime. Here we discuss the introduction and working of the localtime() function in Perl with examples, respectively. You may also have a look at the following articles to learn more –

Weatherproof Seo: How To Stay On Top Of Google Algorithm Changes

This is a sponsored post written by SEMrush. The opinions expressed in this article are the sponsor’s own.

Google’s SERPs change every day. Sometimes it’s you, sometimes it’s your competitors trying to outrun you, and sometimes it’s Google itself updating its algorithms (John Mueller from Google confirmed that algorithm changes happen on a daily basis).

Because of the rivalry, rankings of different domains change constantly. Everyone is searching for new keywords, developing new strategies, and looking for new backlink placements.

Also, looking at the constant updates, one might say that constant fluctuations have actually become a part of Google’s algorithms.

We have collected a list of the most popular tools used to track Google’s volatility. Or, as Obi-Wan Kenobi might say it, to sense if there is any “disturbance in the Force.”

Most of these instruments have been on the market for quite a long time and, unfortunately, do not always keep up with the latest trends.

Two tools that had spikes matching the chatter in the SEO community are SEMrush Sensor and Mozcast. Unfortunately, Mozcast calculates scores one day later so marketers can’t see any changes until the day after the update. One day is a huge period of time that doesn’t allow SEOs to react to the changes fast enough.

At the same time, the SEMrush sensor follows all the changes that occur on SERPs:

Mobile and desktop separate scores.

Changes in SERP features and on SERPs in general (including unconfirmed algorithm updates).

AMP versions and HTTPs website percentages.

Your Personal Score (the SERP changes for our own scope of keywords).

All of this is crafted to ensure that the tool really helps to see if there are any important SERP volatility.

At SEMrush, we don’t stop at offering the data on the dashboard. We analyze it further and transform it in the studies and reports that the SEO community can use to make better data-driven decisions.

Below you’ll find the analysis of all Google SERP fluctuations during the last six months. Fasten your seatbelts as the shakeups are getting stronger and stronger.

Breaking News: Google Has Been Doing It for Ages!

The overall volatility rank during the last six months has been constantly growing from an average of 4 in the beginning of April to almost 5.6 by the start of September.

Some websites survived this September, some didn’t.

SEMrush Sensor detected an unbelievably high score. This means that almost everything has changed on the first page.

The spike was detected in all categories, so not only was the general score insanely high, but SERPs in all categories have suffered. Congratulations to the new winners in search, because if someone loses the top place, someone else gets it.

We also looked at the new top 10, and it turns out that the results in many categories have become more relevant.

The high volatility detected in separate categories (as depicted on the screenshot) is not accidental – it has grown since we started tracking the data.

Tracking Google updates, SERP changes, and your positions for relevant keywords is important.

The data clearly proves, along with tweets from John Mueller and Gary Illyes, that the algorithms are constantly changing, evolving, and improving.

Let’s see if we can dig deeper in SEMrush Sensor data and discover some hidden secrets of Google SERPs?

Still Don’t Believe That Changes on SERP Are Happening Daily?

When we looked into the gathered data further, we discovered that the amount of URLs that have been on the same SERP position for a few days in a row is steadily declining (the relative number dropped from 41 percent to 38.5 percent), whereas the share of the ones that changed their position only to bounce back the next day is growing steadily (from an average of 13.2 percent to an average of 14.51 percent).

This confirms that there are a lot of small Google experiments every day.

Also, the amount of URLs that have shifted by 3-5 positions is growing steadily, while the 1-2 positions shifts are somewhat in stagnation. But the latter number is still larger than the amount of 3 to 5 position shifts.

Beware: Share of Small Domains in the Top 10 Is Steadily Decreasing

We found another trend that confirms what SEO experts talk about: the bigger the domain is, the easier it will stay in top 10.

In other words, if small domains want to push industry giants aside, they will have to put more effort into optimization, and focus on local search and things like content relevance and link building.

Conclusion

Google pays attention to user signals. So make sure the keywords you are targeting are relevant to your content.

And, of course, make sure your website is secure and fast. Otherwise, even random SERP fluctuations won’t get you anywhere close to the first page.

What Does An Algorithm Look Like?

We know that Facebook, Google, and Amazon have algorithms that give us updates, search results, and product recommendations, but what does that actually mean? What qualifies as an algorithm? Can you write one down? What would it look like if you did? Since they run so many parts of our daily lives, it’s important to have a basic sense of what exactly is going on under the hood – and it’s really not as intimidating as it often seems.

Informal definition: algorithms are just recipes

At its most basic, an algorithm is simply a set of well-defined steps that you can follow, generally taking some inputs and producing a different set of outputs. A cupcake recipe can be an algorithm. So are the directions to a friend’s house, playing a piece of sheet music, or the process of looking up a word in a dictionary. Raymond Queneau even printed a book of ten sonnets with lines that can be mixed and matched seamlessly to create 100,000,000,000 original poems. How these algorithms are implemented varies widely, but you don’t need to be familiar with any programming languages to understand the basic logic behind them. For example, the following is an algorithm for giving simple walking directions.

After walking out of your door, turn right.

Walk down the road until you come to Market Street

When you reach Market Street, turn right.

Walk straight until you see a brick building.

Go in the front door.

That’s a very simple algorithm that uses a lot of inputs that humans can easily process; we already know about walking, streets, materials, entering, and all those other things. If we were creating a directional algorithm for a robot, it would have to be a lot longer and more specific, which is what makes many algorithms look so confusing to humans.

More formally: algorithms are clear, unambiguous formulas

One algorithm you probably use every day is Google’s PageRank algorithm, which looks at hundreds of factors about a webpage, runs them through its formula, and assigns it a score. The search results you see in response to your search term are a direct result of that score. It works so well because it follows a clearly defined set of rules that tell it what to look for, what to ignore, and what to do with the information it finds.

To visualize a very simple search process, here’s a linear search algorithm looking for the number 3 in a list of numbers.

list = [1, 3, 5]

Check each item in the list.

As soon as one of the items equals three, return its position.

If three is not in the list, return “Three is not in the list!”

Following these steps, the computer will look at the first number, which is one. Since it doesn’t equal three, it moves on and checks the next number. Since that number is three, it returns something like “The number three is the second item in the list.”

In Python code, a linear sorting algorithm would look like the following image.

All that code is doing is taking a list of numbers, looking at each element in the list, and checking to see if it matches the search term. If nothing does, it just returns “False.” This is an extremely simple algorithm, but whether it’s one line of code or a million, every algorithm in existence operates on the same basic principle: take information, process it according to some preset logic, and get results.

Everyday algorithms

Most of the algorithms that actually run our everyday lives aren’t open source. We don’t know exactly how Google determines what search results to show or how Facebook puts your news feed together, but we can still see the results of those computations. Nonetheless, they are important, and we have a pretty good idea of the basic logic behind them.

Google PageRank works by looking at the number and quality of links leading to and from a webpage, though there are a large number of secret criteria that are constantly being updated to improve results and prevent anyone from gaming the system.

Facebook’s News feed measures the strength of your relationship with people and groups based on your activity, then uses these and some other factors to generate your news feed.

Amazon and Netflix use recommendation algorithms that look at user data, figure out things that each user might want, and show the user those things.

UPS’s ORION system is a huge (1000+ pages!) algorithm, but it can calculate the most efficient route for any delivery while also taking into account all kinds of real-time data and operational parameters, like requested delivery windows.

Artificial intelligence applications like self-driving cars, facial recognition, natural language processing, predictive analytics, and many more rely on algorithms that can take in visual, audio, or digital data, figure out what’s going on, and return appropriate results.

Everything is an algorithm

Once you know what an algorithm looks like, you can’t stop noticing them. They’re not only in our technology, as, after all, they’re in our brains. Everything we do is a result of receiving inputs, processing them, and producing outputs. Most of these processes are stored inside a constantly rearranging black box, but they’re there, behind the scenes, helping us walk around, understand language, and make decisions about things. Humans are equipped to understand algorithms at an instinctual level, so even if computer algorithms are written in indecipherable mathematics and code, they can all be translated into terms we understand.

Image credit: Mandelbrot set image, Websites interlinking to illustrate PageRank, CTP TheoryOfComputation Linear Search, Shell sorting algorithm color bars

Andrew Braun

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.

By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.

Update the detailed information about Working Of Kmeans Algorithm In Opencv? on the Moimoishop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!