{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Riccardo Andreoni",
  "title_listed": "Support Vector Machine with Scikit-Learn: A Friendly Introduction",
  "keywords": "",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/support-vector-machine-with-scikit-learn-a-friendly-introduction-a2969f2ff00d/",
  "publish_date": "2023-10-11",
  "corpus_stage": "",
  "notes": "",
  "id": "66031bc1ba22",
  "collected_at": "2026-10-02T03:22:47",
  "title": "Support Vector Machine with Scikit-Learn: A Friendly Introduction | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Support Vector Machine with Scikit-Learn: A Friendly Introduction\nEvery data scientist should have SVM in their toolbox. Learn how to master this versatile model with a hands-on introduction.\n[Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\nOctober 11, 20238 min read\n![Image source: unsplash.com.](../images/000.jpeg)\nImage source: [unsplash.com](https://unsplash.com/photos/3DkouQeZjp4).\nAmong the available Machine Learning models, there exists one whose versatility makes it a must-have tool for **every data scientist toolbox** : [**Support Vector Machine**](https://en.wikipedia.org/wiki/Support_vector_machine) ([SVM](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html)).\nSVM is a powerful and versatile algorithm, which, at its core, can delineate **optimal hyperplanes** in a high-dimensional space, effectively **segregating the different classes** of a dataset. But it doesn't stop here! Its effectiveness is not limited to **classification** tasks: SVM is well-suited even for **regression** and **outlier detection** tasks.\nOne feature makes the SVM approach particularly effective. Instead of processing the entire dataset, as [KNN does](https://levelup.gitconnected.com/optical-character-recognition-with-knn-classifier-a-step-by-step-guide-b6d7b90e1122), SVM strategically focuses only on the subset of data points located near the decision boundaries. These points are called [_support vectors_](https://www.analyticsvidhya.com/blog/2021/10/support-vector-machinessvm-a-complete-guide-for-beginners/#:~:text=Support%20Vectors%3A%20These%20are%20the,is%20considered%20a%20good%20margin.), and the mathematics behind this unique idea will be simply explained in the upcoming sections.\nBy doing so, SVM Algorithm is **computationally conservative** and ideal for tasks involving medium or even medium-large datasets.\nAs I do in all my articles, I won't just explain the theoretical concepts, but I will also provide you with **coding examples** to familiarize yourself with the [**Scikit-Learn**](https://scikit-learn.org/) (sklearn) [**Python**](https://www.python.org/) library.\nLet's analyze Support Vector Machine (SVM) algorithms, and explore Machine Learning techniques, Python programming, and Data Science applications.\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist), [Computer Science](https://roadmap.sh/computer-science) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n## Linear SVM Classification\nAt its core, SVM classification resembles the elegant simplicity of Linear Algebra. Imagine a dataset in two-dimensional space, with two distinct classes to be separated. Linear SVM tries to separate the two classes with the best possible straight line.\n![Image by the author.](../images/001.png)\nImage by the author.\nWhat does it mean \"best\" in this context? SVM searches for the optimal separation line: a line that not only separates the classes, but does it with the maximum possible distance from the closest training instances of each classes. That distance is called **margin**. The data points that lay on the margin edge are the key element of the linear SVM classifier, and are called **Support Vectors**.\n![Equation of the decision boundary to be optimized.](../images/002.png)\nEquation of the decision boundary to be optimized.\nIt is important to note that the separator is defined exclusively by the Support Vectors. As a consequence, adding more \"off-the-street\" training instances has no impact on the decision boundary. When more training instances that are not Support Vectors are added into the training set, the decision boundary doesn't move and those instances are \"ignored\". This feature is a great advantage of SVM, as it is not required to memorize the entire training set.\nFor an m-dimensional dataset, the separation line becomes a **separation hyperplane** , but the inspiring idea still holds.\nSince the SVM model is based on distances, it is extremely **sensitive to feature scales**. For this reason it is always a good idea to normalize the features' values.\nIn Scikit-Learn we can instantiate a `LinearSVC()` object from the `.svm` module:\npython\n\n```\nimport pandas as pd\nimport sklearn\nfrom sklearn import datasets\n\n# Import the dataset\ndf_ = datasets.load_iris()\ndf = pd.DataFrame()\ndf['petal_length'] = df_['data'][:,2]\ndf['petal_width'] = df_['data'][:,3]\ndf['target'] = df_['target'] == 1\n\n# Define train and test sets\nX_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(df[['petal_length', 'petal_width']], \n                                        df['target'], \n                                        test_size=0.2, \n                                        random_state=42)\n# Normalize data\nscaler = sklearn.preprocessing.StandardScaler()\nX_train = scaler.fit_transform(X_train)\n\n# Instantiate the classifier model\nsvm_classifier = sklearn.svm.LinearSVC()\n# Fit the model with the training data\nsvm_classifier.fit(X_train, y_train)\n# Predict new intances classes\ny_predicted = svm_classifier.predict(scaler.transform(Xtest))\n# Evaluate model's accuracy\naccuracy = sklearn.metrics.accuracy_score(y_test, y_predicted)\nprint(accuracy)\n```\n\nThe resulting accuracy is a mere 66%: not a remarkable result. In the next section, we will understand why the Linear Support Vector Machine classifier didn't perform better and what to do to cope with this.\n### Soft Margin Classification\nAs you can imagine, having a dataset whose classes can be perfercty separated by linear surfaces is a luxury. In a real-world scenario, it doesn't happen and data only needs one outlier to **make it impossible** for a Linear SVM to find a viable decision boundary.\n![Image by the author.](../images/003.png)\nImage by the author.\nAs shown in the image above, in this case, there doesn't exist any line capable of separating the two classes.\nTo cope with real-world scenarios we need to introduce the Soft Margin Support Vector Machine Classification.\nUnlike traditional Linear SVM (also called Hard Margin SVM), Soft Margin SVM doesn't require a rigid separation between the classes, allowing some **elements of flexibility**. By using a Soft Margin SVM, we acknowledge the existence of noisy data points and outliers.\nMore practically, we can specify an hyperparameter `C` which serves as a regularization parameter:\n  * setting `C` to a large value, we enforce a stricter margin, reducing misclassifications\n  * setting `C` to a small value, we encourage a wider margin, allowing a greater number of misclassifications\n\n\n![Increasing C value reduces margin violations.](../images/004.png)\nIncreasing C value reduces margin violations.\nThere are two ways to implement the Soft Margin Linear SVM classifier in Scikit-Learn:\npython\n\n```\n# Method 1\nsvm_classifier_soft = sklearn.svm.LinearSVC(C=10)\nsvm_classifier_soft.fit(X_train, y_train)\n\n# Method 2\nsvm_classifier_soft = sklearn.svm.SVC(kernel='linear', C=10)\nsvm_classifier_soft.fit(X_train, y_train)\n```\n\nRunning these lines of code for the same datasets, we obtain a slighter higher accuracy than the one we obtained for the Hard Margin LinearSVM. Although linear SVM classifiers are efficient and perform well in many scenarios, most datasets' classes are not linearly separable. In these cases, a linear decision boundary yields poor results.\nFortunately for us, SVM classifiers are not limited to linear decision boundaries. Thanks to the [_kernel trick_](https://towardsdatascience.com/the-kernel-trick-c98cdbcaeb3f), they can learn even the most complex separation shapes. The next section will focus on that.\n## Non-Linear SVM Classification\nAs I anticipated, many datasets are **not linearly separable**. Even if we account some flexibility, results obtained through a linear separation line are not optimal. To handle this issue, we can **add more features** , such as polynomial features. Adding new features will transform the original dataset into a higher-dimensional one, where it may be separated by a line or hyperplane.\nConsider this simple example:\n![Non-linearly separable data. Image by the author.](../images/005.png)\nNon-linearly separable data. Image by the author.\nData have only one feature and it is not separable by any straight line. If we add an artificial feature, computed as\n![](../images/body-c3ec0a25b1e638f47cff.png)\nwe obtain the following dataset, which can be separated by a linear boundary:\n![Linearly separable data. Image by the author.](../images/006.png)\nLinearly separable data. Image by the author.\nHowever, adding polynomial features, like we did above, is **not feasible for large and complex datasets**. The resulting number of features would be too high.\nFortunately, there exists a technique called **kernel trick** that makes it possible even with high-degree polynomials. The mathematics behind the kernel trick is not complex, but as I want to focus on the practical implementation, I will leave [this guide](https://people.eecs.berkeley.edu/~jordan/courses/281B-spring04/lectures/lec3.pdf) explaining it.\nTo implement a SVM classifier with a polynomial kernel in Python, we simply use the `SVC()` class and specify the type of kernel we intend to use and its degree:\npython\n\n```\n# Instantiate the classifier object\nSVM_classifier = sklearn.svm.SVC(kernel='poly', degree=5, C=10, coef0=1)\n# Instantiate the scaler object\nscaler = sklearn.preprocessing.StandardScaler()\n\n# Normalize data\nX_train = scaler.fit_transform(X_train)\n\n# Train the classifier\nSVM_classifier.fit(X_train, Y_train)\n```\n\nThe `coef0` hyperparameter acts as a regularization parameter, allowing to control how the model is influenced by high-degree polynomials.\nFinding the correct balance between the `degree`, `C` and`coef0` hyperparameters is not a straightforward task. It is typically recommended to use a Grid Search approach to find some viable values, and later perform a finer manual search to tune them precisely.\n## Similarity Features: Gaussian Radial Basis Function\nPolynomial kernels often work for a variety of machine learning problems, however, there exists a notable technique that often works even better: Similarity Features.\nInstead of adding artificial polynomial features based on the original features' values, we place several _landmarks_ in our high-dimensional feature space and measure the distance from them to each data point. These distance measures become the **new model's features**.\nConsider a training set with two independent features that look like this:\n![Image by the author.](../images/007.png)\nImage by the author.\nBy adding a certain number of landmarks in specific locations, we can create additional features computed as the distance from the data point to each landmark.\n![](../images/body-f17703d90b53fddd0b42.png)\nIn this example, we can place two landmarks in those precise locations. The SVM classifier can then learn to predict as class A the instances close to the landmarks and as class B the ones far away from the landmarks.\nAny distance measure can be used, however, it is proven to be convenient to implement the [**Gaussian Kernel function**](https://pages.stat.wisc.edu/~mchung/teaching/MIA/reading/diffusion.gaussian.kernel.pdf.pdf):\n![](../images/body-c2242e997d3a1a8ae63d.png)\nwhere:\n  * _x_ is the vector containing the data point coordinates\n  * _l_ is the vector containing the landmark coordinates\n  * _gamma_ acts as a regularization hyperparameter\n\n\nThe question now is: \"_Where do I place the landmarks?_ \". The most diffused approach is to place a landmark at each training example location. Having _m_ training examples means creating _m_ landmarks, and, as a consequence, it will result in _m_ new features.\nThe downside of this approach is that for large training sets, we will end up with an equally large number of distance features.\nIn Scikit-Learn a SVM classifier with a Gaussian kernel is implemented as follows:\npython\n\n```\nimport pandas as pd\nimport sklearn\nfrom sklearn import datasets\n\n# Import the dataset\ndf_ = datasets.load_iris()\ndf = pd.DataFrame()\ndf['petal_length'] = df_['data'][:,2]\ndf['petal_width'] = df_['data'][:,3]\ndf['target'] = df_['target'] == 1\n\n# Define train and test sets\nX_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(df[['petal_length', 'petal_width']], \n                                        df['target'], \n                                        test_size=0.2, \n                                        random_state=42)\n# Normalize data\nscaler = sklearn.preprocessing.StandardScaler()\nX_train = scaler.fit_transform(X_train)\n\n# Instantiate the classifier model\nsvm_gaussian_classifier = sklearn.svm.SVC(kernel='rbf', gamma=6, C=0.001)\n# Fit the model with the training data\nsvm_gaussian_classifier.fit(X_train, y_train)\n# Predict new intances classes\ny_predicted = svm_gaussian_classifier.predict(scaler.transform(X_test))\n# Evaluate model's accuracy\naccuracy = sklearn.metrics.accuracy_score(y_test, y_predicted)\n```\n\n## Conclusion\nIn this post, we detailed the theory of this versatile and powerful model, and we understood how easy it is to implement it in Python through the Scikit-Learn library.\nI conclude this introductory guide by delineating the pros and cons of Support Vector Machine model.\nWithout any question, the strength of SVM coincide with its **accuracy in high-dimensional spaces** , making it ideal for data with numerous features, like images or genetic data. Additionally, I must remark SVM **versatility** : beyond classification, it seamlessly adapts to regression and anomaly detection tasks. Finally, on the pros side, I must point out its **flexibility**. SVM ability to handle non-linear relationships through different kernel functions, grants it a vast application spectrum.\nAs we all know the mantra \"_there is no free meal in Machine Learning_ \", we must acknowledge SVM cons. First of all, SVM can easily be **affected by noisy data** , as we saw in the **Linear SVM** section. **Scalability** is also an Achilles heel for SVM: training large datasets with SVM can be computationally intensive and demanding.\nAs I reach the end of this guide, I need to point out that, despite having touched all the most relevant aspects of SVM, its field extends far beyond the insight provided here. For this reason, I recommend digging into the resources and references attached to this article.\n* * *\nIf you liked this story, consider following me to be notified of my upcoming projects and articles!\nHere are some of my past projects:\n> [**Social Network Analysis with NetworkX: A Gentle Introduction**](https://towardsdatascience.com/social-network-analysis-with-networkx-a-gentle-introduction-6123eddced3)\n> [**Ensemble Learning with Scikit-Learn: A Friendly Introduction**](https://towardsdatascience.com/ensemble-learning-with-scikit-learn-a-friendly-introduction-5dd64650de6c)\n> [**Use Deep Learning to Generate Fantasy Names: Build a Language Model from Scratch**](https://towardsdatascience.com/use-deep-learning-to-generate-fantasy-character-names-build-a-language-model-from-scratch-792b13629efa)\n## References\n  * [Machine Learning with Python](https://www.coursera.org/learn/machine-learning-with-python)\n  * [Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition - Aurélien Géron](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/)\n  * [Scikit-Learn SVM documentation](https://scikit-learn.org/stable/modules/svm.html)\n  * [Machine Learning Specialization](https://www.coursera.org/specializations/machine-learning-introduction)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-34347b17fbf8612c4a0c.jpeg)\nWritten By\n## [Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[See all from Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Getting Started](https://towardsdatascience.com/tag/getting-started/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Programming](https://towardsdatascience.com/tag/programming/)[Support Vector Machine](https://towardsdatascience.com/tag/support-vector-machine/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fsupport-vector-machine-with-scikit-learn-a-friendly-introduction-a2969f2ff00d%2F&title=Support%20Vector%20Machine%20with%20Scikit-Learn%3A%20A%20Friendly%20Introduction)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fsupport-vector-machine-with-scikit-learn-a-friendly-introduction-a2969f2ff00d%2F&title=Support%20Vector%20Machine%20with%20Scikit-Learn%3A%20A%20Friendly%20Introduction)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fsupport-vector-machine-with-scikit-learn-a-friendly-introduction-a2969f2ff00d%2F&text=Support%20Vector%20Machine%20with%20Scikit-Learn%3A%20A%20Friendly%20Introduction)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/008.jpeg)](https://towardsdatascience.com/train-neural-net-for-semantic-segmentation-with-pytorch-in-50-lines-of-code-830c71a6544f/)\n## [Train a neural net for semantic segmentation in 50 lines of code, with Pytorch](https://towardsdatascience.com/train-neural-net-for-semantic-segmentation-with-pytorch-in-50-lines-of-code-830c71a6544f/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHow to train a neural net for semantic segmentation in less than 50 lines of code (40 if you exclude imports). The goal here is to give the...\n[Sagi eppel](https://towardsdatascience.com/author/sagieppel/)\nDecember 3, 202110 min read\n  * [![](../images/009.png)](https://towardsdatascience.com/an-alternative-approach-to-visualizing-feature-relationships-in-large-datasets-925ab257d772/)\n## [An Alternative Approach to Visualizing Feature Relationships in Large Datasets](https://towardsdatascience.com/an-alternative-approach-to-visualizing-feature-relationships-in-large-datasets-925ab257d772/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHow to make those crowded scatterplots more informative\n[Zvonimir Boban](https://towardsdatascience.com/author/zvonimir.boban.mef/)\nSeptember 28, 20235 min read\n  * [![](../images/010.jpg)](https://towardsdatascience.com/regression-basics-code-walk-through-c2eac24da2e9/)\n## [Regression Basics: Code Walk-Through](https://towardsdatascience.com/regression-basics-code-walk-through-c2eac24da2e9/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nDiscover the Fundamentals of Regression by Predicting Car Sale Prices\n[Jewel Britton](https://towardsdatascience.com/author/jewelbritton9/)\nAugust 3, 202014 min read\n  * [![](../images/011.jpg)](https://towardsdatascience.com/keep-your-data-clean-with-data-testing-b84b4f789fa1/)\n## [Keep your data clean with data testing](https://towardsdatascience.com/keep-your-data-clean-with-data-testing-b84b4f789fa1/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nApply tests to your data and improve the quality of your pipeline with great-expectations\n[Laurenz Reitsam](https://towardsdatascience.com/author/laurenz.reitsam/)\nOctober 18, 20205 min read\n  * [![](../images/012.png)](https://towardsdatascience.com/how-id-learn-machine-learning-if-i-could-start-over-c68d697e6a8a/)\n## [How I’d Learn Machine Learning (If I Could Start Over)](https://towardsdatascience.com/how-id-learn-machine-learning-if-i-could-start-over-c68d697e6a8a/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA full breakdown of how you can learn machine learning this year effectively\n[Egor Howell](https://towardsdatascience.com/author/egorhowell/)\nJanuary 27, 20249 min read\n  * [![](../images/013.webp)](https://towardsdatascience.com/why-you-think-like-a-bayesian-but-were-taught-like-a-frequentist/)\n## [Why You Think Like a Bayesian but Were Taught Like a Frequentist](https://towardsdatascience.com/why-you-think-like-a-bayesian-but-were-taught-like-a-frequentist/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nFrom a chocolate bar with no price tag to a marketing mix model in PyMC, and the 200-year-old integral that stood in between.\n[Spyros Georgopoulos](https://towardsdatascience.com/author/spyros.georgopoulos/)\nSeptember 17, 202622 min read\n  * [![](../images/014.jpg)](https://towardsdatascience.com/illuminating-the-black-box-of-ai-ddea07e65c35/)\n## [Illuminating the Black Box of Textual GenAI](https://towardsdatascience.com/illuminating-the-black-box-of-ai-ddea07e65c35/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nThe Need for Insights\n[Anthony Alcaraz](https://towardsdatascience.com/author/alcarazanthony1/)\nDecember 17, 20239 min read\n  * [![](../images/015.png)](https://towardsdatascience.com/how-well-does-self-supervised-learning-perform-in-the-real-world-ece18b2d45f6/)\n## [How Well Does Self-Supervised Learning Perform In The Real World?](https://towardsdatascience.com/how-well-does-self-supervised-learning-perform-in-the-real-world-ece18b2d45f6/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nPre-training a model on random internet images instead of ImageNet\n[Leon Sick](https://towardsdatascience.com/author/leon.sick/)\nDecember 15, 20217 min read\n  * [![](../images/016.jpeg)](https://towardsdatascience.com/predicting-churn-with-user-log-data-from-a-digital-music-streaming-app-7c30d7206daf/)\n## [Predicting Churn with user log data from a digital music streaming app](https://towardsdatascience.com/predicting-churn-with-user-log-data-from-a-digital-music-streaming-app-7c30d7206daf/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nPredicting Churn is one of the most interesting things a company could do in order to better understand clients and anticipate changes in...\n[Lucas Correa](https://towardsdatascience.com/author/lukec-correa/)\nOctober 27, 202011 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "metadata": {
    "title": "Support Vector Machine with Scikit-Learn: A Friendly Introduction | Towards Data Science",
    "description": "Every data scientist should have SVM in their toolbox. Learn how to master this versatile model with a hands-on introduction.",
    "keywords": null,
    "author": "Riccardo Andreoni",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Support Vector Machine with Scikit-Learn: A Friendly Introduction",
    "og:description": "Every data scientist should have SVM in their toolbox. Learn how to master this versatile model with a hands-on introduction.",
    "og:url": "https://towardsdatascience.com/support-vector-machine-with-scikit-learn-a-friendly-introduction-a2969f2ff00d/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1Wfq08Av9TBELJWz0kywiTg-scaled.jpeg",
    "og:image:width": "2560",
    "og:image:height": "1284",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Riccardo Andreoni",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "8 min read",
    "article:published_time": "2023-10-11T03:56:32.000Z",
    "article:modified_time": "2023-10-11T03:56:32.000Z",
    "article:author": "https://towardsdatascience.com/author/riccardo.andreoni/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/66031bc1ba22/code/block_000.txt",
      "chars": 1012
    },
    {
      "language": "txt",
      "file": "attachments/66031bc1ba22/code/block_001.txt",
      "chars": 218
    },
    {
      "language": "txt",
      "file": "attachments/66031bc1ba22/code/block_002.txt",
      "chars": 308
    },
    {
      "language": "txt",
      "file": "attachments/66031bc1ba22/code/block_003.txt",
      "chars": 1048
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:54:22Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:54:22Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:54:22Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:54:22Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/riccardo.andreoni/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/the-kernel-trick-c98cdbcaeb3f"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/social-network-analysis-with-networkx-a-gentle-introduction-6123eddced3"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/ensemble-learning-with-scikit-learn-a-friendly-introduction-5dd64650de6c"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/use-deep-learning-to-generate-fantasy-character-names-build-a-language-model-from-scratch-792b13629efa"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/getting-started/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/support-vector-machine/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/train-neural-net-for-semantic-segmentation-with-pytorch-in-50-lines-of-code-830c71a6544f/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/sagieppel/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/photos/3DkouQeZjp4"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Support_vector_machine"
    },
    {
      "type": "external",
      "href": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html"
    },
    {
      "type": "external",
      "href": "https://levelup.gitconnected.com/optical-character-recognition-with-knn-classifier-a-step-by-step-guide-b6d7b90e1122"
    },
    {
      "type": "external",
      "href": "https://www.analyticsvidhya.com/blog/2021/10/support-vector-machinessvm-a-complete-guide-for-beginners/"
    },
    {
      "type": "external",
      "href": "https://scikit-learn.org/"
    },
    {
      "type": "external",
      "href": "https://www.python.org/"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/computer-science"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://people.eecs.berkeley.edu/~jordan/courses/281B-spring04/lectures/lec3.pdf"
    },
    {
      "type": "external",
      "href": "https://pages.stat.wisc.edu/~mchung/teaching/MIA/reading/diffusion.gaussian.kernel.pdf.pdf"
    },
    {
      "type": "external",
      "href": "https://www.coursera.org/learn/machine-learning-with-python"
    },
    {
      "type": "external",
      "href": "https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/"
    },
    {
      "type": "external",
      "href": "https://scikit-learn.org/stable/modules/svm.html"
    },
    {
      "type": "external",
      "href": "https://www.coursera.org/specializations/machine-learning-introduction"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Support+Vector+Machine+with+Scikit-Learn%3A+A+Friendly+Introduction&u=https%3A%2F%2Ftowardsdatascience.com%2Fsupport-vector-machine-with-scikit-learn-a-friendly-introduction-a2969f2ff00d%2F"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:28:29Z",
  "source_url": "https://towardsdatascience.com/support-vector-machine-with-scikit-learn-a-friendly-introduction-a2969f2ff00d/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Support Vector Machine with Scikit-Learn: A Friendly Introduction\nEvery data scientist should have SVM in their toolbox. Learn how to master this versatile model with a hands-on introduction.\n[Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\nOctober 11, 20238 min read\n![Image source: unsplash.com.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1Wfq08Av9TBELJWz0kywiTg-scaled.jpeg)\nImage source: [unsplash.com](https://unsplash.com/photos/3DkouQeZjp4).\nAmong the available Machine Learning models, there exists one whose versatility makes it a must-have tool for **every data scientist toolbox** : [**Support Vector Machine**](https://en.wikipedia.org/wiki/Support_vector_machine) ([SVM](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html)).\nSVM is a powerful and versatile algorithm, which, at its core, can delineate **optimal hyperplanes** in a high-dimensional space, effectively **segregating the different classes** of a dataset. But it doesn't stop here! Its effectiveness is not limited to **classification** tasks: SVM is well-suited even for **regression** and **outlier detection** tasks.\nOne feature makes the SVM approach particularly effective. Instead of processing the entire dataset, as [KNN does](https://levelup.gitconnected.com/optical-character-recognition-with-knn-classifier-a-step-by-step-guide-b6d7b90e1122), SVM strategically focuses only on the subset of data points located near the decision boundaries. These points are called [_support vectors_](https://www.analyticsvidhya.com/blog/2021/10/support-vector-machinessvm-a-complete-guide-for-beginners/#:~:text=Support%20Vectors%3A%20These%20are%20the,is%20considered%20a%20good%20margin.), and the mathematics behind this unique idea will be simply explained in the upcoming sections.\nBy doing so, SVM Algorithm is **computationally conservative** and ideal for tasks involving medium or even medium-large datasets.\nAs I do in all my articles, I won't just explain the theoretical concepts, but I will also provide you with **coding examples** to familiarize yourself with the [**Scikit-Learn**](https://scikit-learn.org/) (sklearn) [**Python**](https://www.python.org/) library.\nLet's analyze Support Vector Machine (SVM) algorithms, and explore Machine Learning techniques, Python programming, and Data Science applications.\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist), [Computer Science](https://roadmap.sh/computer-science) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n## Linear SVM Classification\nAt its core, SVM classification resembles the elegant simplicity of Linear Algebra. Imagine a dataset in two-dimensional space, with two distinct classes to be separated. Linear SVM tries to separate the two classes with the best possible straight line.\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1myJAQOLNWdeNCJvTWnNY5Q.png)\nImage by the author.\nWhat does it mean \"best\" in this context? SVM searches for the optimal separation line: a line that not only separates the classes, but does it with the maximum possible distance from the closest training instances of each classes. That distance is called **margin**. The data points that lay on the margin edge are the key element of the linear SVM classifier, and are called **Support Vectors**.\n![Equation of the decision boundary to be optimized.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/12Vx-rcDVn9FPJzPhHg3V2Q.png)\nEquation of the decision boundary to be optimized.\nIt is important to note that the separator is defined exclusively by the Support Vectors. As a consequence, adding more \"off-the-street\" training instances has no impact on the decision boundary. When more training instances that are not Support Vectors are added into the training set, the decision boundary doesn't move and those instances are \"ignored\". This feature is a great advantage of SVM, as it is not required to memorize the entire training set.\nFor an m-dimensional dataset, the separation line becomes a **separation hyperplane** , but the inspiring idea still holds.\nSince the SVM model is based on distances, it is extremely **sensitive to feature scales**. For this reason it is always a good idea to normalize the features' values.\nIn Scikit-Learn we can instantiate a `LinearSVC()` object from the `.svm` module:\npython\n\n```\nimport pandas as pd\nimport sklearn\nfrom sklearn import datasets\n\n# Import the dataset\ndf_ = datasets.load_iris()\ndf = pd.DataFrame()\ndf['petal_length'] = df_['data'][:,2]\ndf['petal_width'] = df_['data'][:,3]\ndf['target'] = df_['target'] == 1\n\n# Define train and test sets\nX_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(df[['petal_length', 'petal_width']], \n                                        df['target'], \n                                        test_size=0.2, \n                                        random_state=42)\n# Normalize data\nscaler = sklearn.preprocessing.StandardScaler()\nX_train = scaler.fit_transform(X_train)\n\n# Instantiate the classifier model\nsvm_classifier = sklearn.svm.LinearSVC()\n# Fit the model with the training data\nsvm_classifier.fit(X_train, y_train)\n# Predict new intances classes\ny_predicted = svm_classifier.predict(scaler.transform(Xtest))\n# Evaluate model's accuracy\naccuracy = sklearn.metrics.accuracy_score(y_test, y_predicted)\nprint(accuracy)\n```\n\nThe resulting accuracy is a mere 66%: not a remarkable result. In the next section, we will understand why the Linear Support Vector Machine classifier didn't perform better and what to do to cope with this.\n### Soft Margin Classification\nAs you can imagine, having a dataset whose classes can be perfercty separated by linear surfaces is a luxury. In a real-world scenario, it doesn't happen and data only needs one outlier to **make it impossible** for a Linear SVM to find a viable decision boundary.\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1bXlp7LVAPhIay-Pk0MxdlA.png)\nImage by the author.\nAs shown in the image above, in this case, there doesn't exist any line capable of separating the two classes.\nTo cope with real-world scenarios we need to introduce the Soft Margin Support Vector Machine Classification.\nUnlike traditional Linear SVM (also called Hard Margin SVM), Soft Margin SVM doesn't require a rigid separation between the classes, allowing some **elements of flexibility**. By using a Soft Margin SVM, we acknowledge the existence of noisy data points and outliers.\nMore practically, we can specify an hyperparameter `C` which serves as a regularization parameter:\n  * setting `C` to a large value, we enforce a stricter margin, reducing misclassifications\n  * setting `C` to a small value, we encourage a wider margin, allowing a greater number of misclassifications\n\n\n![Increasing C value reduces margin violations.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1orBa_e2jgfKHkgGkx4OVwA.png)\nIncreasing C value reduces margin violations.\nThere are two ways to implement the Soft Margin Linear SVM classifier in Scikit-Learn:\npython\n\n```\n# Method 1\nsvm_classifier_soft = sklearn.svm.LinearSVC(C=10)\nsvm_classifier_soft.fit(X_train, y_train)\n\n# Method 2\nsvm_classifier_soft = sklearn.svm.SVC(kernel='linear', C=10)\nsvm_classifier_soft.fit(X_train, y_train)\n```\n\nRunning these lines of code for the same datasets, we obtain a slighter higher accuracy than the one we obtained for the Hard Margin LinearSVM. Although linear SVM classifiers are efficient and perform well in many scenarios, most datasets' classes are not linearly separable. In these cases, a linear decision boundary yields poor results.\nFortunately for us, SVM classifiers are not limited to linear decision boundaries. Thanks to the [_kernel trick_](https://towardsdatascience.com/the-kernel-trick-c98cdbcaeb3f), they can learn even the most complex separation shapes. The next section will focus on that.\n## Non-Linear SVM Classification\nAs I anticipated, many datasets are **not linearly separable**. Even if we account some flexibility, results obtained through a linear separation line are not optimal. To handle this issue, we can **add more features** , such as polynomial features. Adding new features will transform the original dataset into a higher-dimensional one, where it may be separated by a line or hyperplane.\nConsider this simple example:\n![Non-linearly separable data. Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1iA4RW90Q97ZHDw8JxFC1EQ.png)\nNon-linearly separable data. Image by the author.\nData have only one feature and it is not separable by any straight line. If we add an artificial feature, computed as\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1X6YxDUBe4fKS210KssHIOw.png)\nwe obtain the following dataset, which can be separated by a linear boundary:\n![Linearly separable data. Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1frRfJhBQZzYhtl4ECZKJWw.png)\nLinearly separable data. Image by the author.\nHowever, adding polynomial features, like we did above, is **not feasible for large and complex datasets**. The resulting number of features would be too high.\nFortunately, there exists a technique called **kernel trick** that makes it possible even with high-degree polynomials. The mathematics behind the kernel trick is not complex, but as I want to focus on the practical implementation, I will leave [this guide](https://people.eecs.berkeley.edu/~jordan/courses/281B-spring04/lectures/lec3.pdf) explaining it.\nTo implement a SVM classifier with a polynomial kernel in Python, we simply use the `SVC()` class and specify the type of kernel we intend to use and its degree:\npython\n\n```\n# Instantiate the classifier object\nSVM_classifier = sklearn.svm.SVC(kernel='poly', degree=5, C=10, coef0=1)\n# Instantiate the scaler object\nscaler = sklearn.preprocessing.StandardScaler()\n\n# Normalize data\nX_train = scaler.fit_transform(X_train)\n\n# Train the classifier\nSVM_classifier.fit(X_train, Y_train)\n```\n\nThe `coef0` hyperparameter acts as a regularization parameter, allowing to control how the model is influenced by high-degree polynomials.\nFinding the correct balance between the `degree`, `C` and`coef0` hyperparameters is not a straightforward task. It is typically recommended to use a Grid Search approach to find some viable values, and later perform a finer manual search to tune them precisely.\n## Similarity Features: Gaussian Radial Basis Function\nPolynomial kernels often work for a variety of machine learning problems, however, there exists a notable technique that often works even better: Similarity Features.\nInstead of adding artificial polynomial features based on the original features' values, we place several _landmarks_ in our high-dimensional feature space and measure the distance from them to each data point. These distance measures become the **new model's features**.\nConsider a training set with two independent features that look like this:\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1QsgVygdABjiW7U0Jg-e6Yw.png)\nImage by the author.\nBy adding a certain number of landmarks in specific locations, we can create additional features computed as the distance from the data point to each landmark.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1gNLr9PLFIVpQAsqCYcdcbA.png)\nIn this example, we can place two landmarks in those precise locations. The SVM classifier can then learn to predict as class A the instances close to the landmarks and as class B the ones far away from the landmarks.\nAny distance measure can be used, however, it is proven to be convenient to implement the [**Gaussian Kernel function**](https://pages.stat.wisc.edu/~mchung/teaching/MIA/reading/diffusion.gaussian.kernel.pdf.pdf):\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/1jfGRnT8iNmi_xYOyS904Lw.png)\nwhere:\n  * _x_ is the vector containing the data point coordinates\n  * _l_ is the vector containing the landmark coordinates\n  * _gamma_ acts as a regularization hyperparameter\n\n\nThe question now is: \"_Where do I place the landmarks?_ \". The most diffused approach is to place a landmark at each training example location. Having _m_ training examples means creating _m_ landmarks, and, as a consequence, it will result in _m_ new features.\nThe downside of this approach is that for large training sets, we will end up with an equally large number of distance features.\nIn Scikit-Learn a SVM classifier with a Gaussian kernel is implemented as follows:\npython\n\n```\nimport pandas as pd\nimport sklearn\nfrom sklearn import datasets\n\n# Import the dataset\ndf_ = datasets.load_iris()\ndf = pd.DataFrame()\ndf['petal_length'] = df_['data'][:,2]\ndf['petal_width'] = df_['data'][:,3]\ndf['target'] = df_['target'] == 1\n\n# Define train and test sets\nX_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(df[['petal_length', 'petal_width']], \n                                        df['target'], \n                                        test_size=0.2, \n                                        random_state=42)\n# Normalize data\nscaler = sklearn.preprocessing.StandardScaler()\nX_train = scaler.fit_transform(X_train)\n\n# Instantiate the classifier model\nsvm_gaussian_classifier = sklearn.svm.SVC(kernel='rbf', gamma=6, C=0.001)\n# Fit the model with the training data\nsvm_gaussian_classifier.fit(X_train, y_train)\n# Predict new intances classes\ny_predicted = svm_gaussian_classifier.predict(scaler.transform(X_test))\n# Evaluate model's accuracy\naccuracy = sklearn.metrics.accuracy_score(y_test, y_predicted)\n```\n\n## Conclusion\nIn this post, we detailed the theory of this versatile and powerful model, and we understood how easy it is to implement it in Python through the Scikit-Learn library.\nI conclude this introductory guide by delineating the pros and cons of Support Vector Machine model.\nWithout any question, the strength of SVM coincide with its **accuracy in high-dimensional spaces** , making it ideal for data with numerous features, like images or genetic data. Additionally, I must remark SVM **versatility** : beyond classification, it seamlessly adapts to regression and anomaly detection tasks. Finally, on the pros side, I must point out its **flexibility**. SVM ability to handle non-linear relationships through different kernel functions, grants it a vast application spectrum.\nAs we all know the mantra \"_there is no free meal in Machine Learning_ \", we must acknowledge SVM cons. First of all, SVM can easily be **affected by noisy data** , as we saw in the **Linear SVM** section. **Scalability** is also an Achilles heel for SVM: training large datasets with SVM can be computationally intensive and demanding.\nAs I reach the end of this guide, I need to point out that, despite having touched all the most relevant aspects of SVM, its field extends far beyond the insight provided here. For this reason, I recommend digging into the resources and references attached to this article.\n* * *\nIf you liked this story, consider following me to be notified of my upcoming projects and articles!\nHere are some of my past projects:\n> [**Social Network Analysis with NetworkX: A Gentle Introduction**](https://towardsdatascience.com/social-network-analysis-with-networkx-a-gentle-introduction-6123eddced3)\n> [**Ensemble Learning with Scikit-Learn: A Friendly Introduction**](https://towardsdatascience.com/ensemble-learning-with-scikit-learn-a-friendly-introduction-5dd64650de6c)\n> [**Use Deep Learning to Generate Fantasy Names: Build a Language Model from Scratch**](https://towardsdatascience.com/use-deep-learning-to-generate-fantasy-character-names-build-a-language-model-from-scratch-792b13629efa)\n## References\n  * [Machine Learning with Python](https://www.coursera.org/learn/machine-learning-with-python)\n  * [Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition - Aurélien Géron](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/)\n  * [Scikit-Learn SVM documentation](https://scikit-learn.org/stable/modules/svm.html)\n  * [Machine Learning Specialization](https://www.coursera.org/specializations/machine-learning-introduction)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657095428_xaezyc.jpeg)\nWritten By\n## [Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[See all from Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Getting Started](https://towardsdatascience.com/tag/getting-started/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Programming](https://towardsdatascience.com/tag/programming/)[Support Vector Machine](https://towardsdatascience.com/tag/support-vector-machine/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fsupport-vector-machine-with-scikit-learn-a-friendly-introduction-a2969f2ff00d%2F&title=Support%20Vector%20Machine%20with%20Scikit-Learn%3A%20A%20Friendly%20Introduction)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fsupport-vector-machine-with-scikit-learn-a-friendly-introduction-a2969f2ff00d%2F&title=Support%20Vector%20Machine%20with%20Scikit-Learn%3A%20A%20Friendly%20Introduction)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fsupport-vector-machine-with-scikit-learn-a-friendly-introduction-a2969f2ff00d%2F&text=Support%20Vector%20Machine%20with%20Scikit-Learn%3A%20A%20Friendly%20Introduction)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1bC19gh9oq8yx8saKSWhVJQ-scaled.jpeg)](https://towardsdatascience.com/train-neural-net-for-semantic-segmentation-with-pytorch-in-50-lines-of-code-830c71a6544f/)\n## [Train a neural net for semantic segmentation in 50 lines of code, with Pytorch](https://towardsdatascience.com/train-neural-net-for-semantic-segmentation-with-pytorch-in-50-lines-of-code-830c71a6544f/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHow to train a neural net for semantic segmentation in less than 50 lines of code (40 if you exclude imports). The goal here is to give the...\n[Sagi eppel](https://towardsdatascience.com/author/sagieppel/)\nDecember 3, 202110 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/1Ec9ZtGyVfPmHXu6Ns8qhnA.png)](https://towardsdatascience.com/an-alternative-approach-to-visualizing-feature-relationships-in-large-datasets-925ab257d772/)\n## [An Alternative Approach to Visualizing Feature Relationships in Large Datasets](https://towardsdatascience.com/an-alternative-approach-to-visualizing-feature-relationships-in-large-datasets-925ab257d772/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHow to make those crowded scatterplots more informative\n[Zvonimir Boban](https://towardsdatascience.com/author/zvonimir.boban.mef/)\nSeptember 28, 20235 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/08/0xy9ddYccr9GPfDau-scaled.jpg)](https://towardsdatascience.com/regression-basics-code-walk-through-c2eac24da2e9/)\n## [Regression Basics: Code Walk-Through](https://towardsdatascience.com/regression-basics-code-walk-through-c2eac24da2e9/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nDiscover the Fundamentals of Regression by Predicting Car Sale Prices\n[Jewel Britton](https://towardsdatascience.com/author/jewelbritton9/)\nAugust 3, 202014 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0r7qBwhogCeRKOBp4-scaled.jpg)](https://towardsdatascience.com/keep-your-data-clean-with-data-testing-b84b4f789fa1/)\n## [Keep your data clean with data testing](https://towardsdatascience.com/keep-your-data-clean-with-data-testing-b84b4f789fa1/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nApply tests to your data and improve the quality of your pipeline with great-expectations\n[Laurenz Reitsam](https://towardsdatascience.com/author/laurenz.reitsam/)\nOctober 18, 20205 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1I0CTrhEj3Ad7K1Vwk8qe-w.png)](https://towardsdatascience.com/how-id-learn-machine-learning-if-i-could-start-over-c68d697e6a8a/)\n## [How I’d Learn Machine Learning (If I Could Start Over)](https://towardsdatascience.com/how-id-learn-machine-learning-if-i-could-start-over-c68d697e6a8a/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA full breakdown of how you can learn machine learning this year effectively\n[Egor Howell](https://towardsdatascience.com/author/egorhowell/)\nJanuary 27, 20249 min read\n  * [![](https://assets.insightmediagroup.io/media/1789234626167_78iawg.webp)](https://towardsdatascience.com/why-you-think-like-a-bayesian-but-were-taught-like-a-frequentist/)\n## [Why You Think Like a Bayesian but Were Taught Like a Frequentist](https://towardsdatascience.com/why-you-think-like-a-bayesian-but-were-taught-like-a-frequentist/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nFrom a chocolate bar with no price tag to a marketing mix model in PyMC, and the 200-year-old integral that stood in between.\n[Spyros Georgopoulos](https://towardsdatascience.com/author/spyros.georgopoulos/)\nSeptember 17, 202622 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/02bXgNg8oXO3MYcMG.jpg)](https://towardsdatascience.com/illuminating-the-black-box-of-ai-ddea07e65c35/)\n## [Illuminating the Black Box of Textual GenAI](https://towardsdatascience.com/illuminating-the-black-box-of-ai-ddea07e65c35/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nThe Need for Insights\n[Anthony Alcaraz](https://towardsdatascience.com/author/alcarazanthony1/)\nDecember 17, 20239 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1-qx84N7ropPj7BQwMtf3cQ.png)](https://towardsdatascience.com/how-well-does-self-supervised-learning-perform-in-the-real-world-ece18b2d45f6/)\n## [How Well Does Self-Supervised Learning Perform In The Real World?](https://towardsdatascience.com/how-well-does-self-supervised-learning-perform-in-the-real-world-ece18b2d45f6/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nPre-training a model on random internet images instead of ImageNet\n[Leon Sick](https://towardsdatascience.com/author/leon.sick/)\nDecember 15, 20217 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/1U6VIU_lFdUPgIuxyaKtYVg-scaled.jpeg)](https://towardsdatascience.com/predicting-churn-with-user-log-data-from-a-digital-music-streaming-app-7c30d7206daf/)\n## [Predicting Churn with user log data from a digital music streaming app](https://towardsdatascience.com/predicting-churn-with-user-log-data-from-a-digital-music-streaming-app-7c30d7206daf/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nPredicting Churn is one of the most interesting things a company could do in order to better understand clients and anticipate changes in...\n[Lucas Correa](https://towardsdatascience.com/author/lukec-correa/)\nOctober 27, 202011 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "body_base_path": "attachments/66031bc1ba22/pages/",
  "body_markdown_path": "attachments/66031bc1ba22/pages/archived-body.md",
  "local_html": "attachments/66031bc1ba22/pages/archived-body.html",
  "body_source": "prior_capture"
}