Use Scikit-Learn to quickly master machine learning prediction methods
In this article, we will discuss the differences between prediction functions and their uses.
In machine learning, the predict and predict_proba, predict_log_proba and decision_function methods are all used to make predictions based on the trained model.
predict method
Use the predict method to predict binary classification or multivariate classification and output prediction labels. For example, if you have trained a logistic regression model to predict whether a customer will buy a product, you can use the predict method to predict whether a new customer will buy the product.
We will use the breast cancer dataset from scikit-learn. This dataset contains tumor observations and corresponding labels of whether the tumor is malignant or benign.
import numpy as npfrom sklearn.svm import SVCfrom sklearn.preprocessing import StandardScalerfrom sklearn.pipeline import make_pipelineimport matplotlib.pyplot as pltfrom sklearn.datasets import load_breast_cancer# 加载数据集dataset = load_breast_cancer(as_frame=True)# 创建特征和目标X = dataset['data']y = dataset['target']# 将数据集分割成训练集和测试集from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y , test_size=0.25, random_state=0)# 我们创建一个简单的管道来规范数据并使用`SVC`分类器训练模型svc_clf = make_pipeline(StandardScaler(),SVC(max_iter=1000, probability=True))svc_clf.fit(X_train, y_train)
# 我们正在预测X_test的第一个条目print(svc_clf.predict(X_test[:1]))
# 预测X_test的第一个条目属于哪一类[0]
predict_proba method
Use the predict_proba function to make a probability prediction for each category and return the possible probability estimate of each category label. In binary or multivariate classification problems, this approach is commonly used to determine the probability of each possible outcome. For example, if you have trained a model to classify images of animals into cats, dogs, and horses, you can use the predict_proba method to obtain probability estimates for each category label.
print(svc_clf.predict_proba(X_test[:1]))
[[0.99848307 0.00151693]]
predict_log_proba method
The predict_log_proba method is similar to predict_proba, but it returns the logarithm of the probability estimate instead of the raw probability. This is very useful for dealing with very small or very large probability values, because it can avoid numerical underflow or overflow problems.
print(svc_clf.predict_log_proba(X_test[:1]))rrree
decision_function method
Linear binary classification models can utilize the decision_function method. It generates a score for each input data point, which can be used to infer its corresponding class label. Thresholds that classify data points as positive or negative can be set based on application or domain knowledge.
[[-1.51808474e-03 -6.49106473e+00]]
print(svc_clf.decision_function(X_test[:1]))
Summary
- Use predict for binary or multivariate classification problems when you want to get the predicted class label of the input data.
- Use predict_proba for binary or multivariate classification problems when you want to obtain a probability estimate for each possible class label.
- Use predict_log_proba when you need to deal with very small or very large probability values, or when you want to avoid numerical underflow or overflow problems.
- Use decision_function to handle binary classification problems with linear models when you want to get the score for each input data point.
Note: Some classifiers' prediction methods may be incomplete or require additional parameters to access the function. For example: SVC needs to set the probability parameter to True to use probability prediction.
The above is the detailed content of Use Scikit-Learn to quickly master machine learning prediction methods. For more information, please follow other related articles on the PHP Chinese website!

In John Rawls' seminal 1971 book The Theory of Justice, he proposed a thought experiment that we should take as the core of today's AI design and use decision-making: the veil of ignorance. This philosophy provides a simple tool for understanding equity and also provides a blueprint for leaders to use this understanding to design and implement AI equitably. Imagine that you are making rules for a new society. But there is a premise: you don’t know in advance what role you will play in this society. You may end up being rich or poor, healthy or disabled, belonging to a majority or marginal minority. Operating under this "veil of ignorance" prevents rule makers from making decisions that benefit themselves. On the contrary, people will be more motivated to formulate public

Numerous companies specialize in robotic process automation (RPA), offering bots to automate repetitive tasks—UiPath, Automation Anywhere, Blue Prism, and others. Meanwhile, process mining, orchestration, and intelligent document processing speciali

The future of AI is moving beyond simple word prediction and conversational simulation; AI agents are emerging, capable of independent action and task completion. This shift is already evident in tools like Anthropic's Claude. AI Agents: Research a

Rapid technological advancements necessitate a forward-looking perspective on the future of work. What happens when AI transcends mere productivity enhancement and begins shaping our societal structures? Topher McDougal's upcoming book, Gaia Wakes:

Product classification, often involving complex codes like "HS 8471.30" from systems such as the Harmonized System (HS), is crucial for international trade and domestic sales. These codes ensure correct tax application, impacting every inv

The future of energy consumption in data centers and climate technology investment This article explores the surge in energy consumption in AI-driven data centers and its impact on climate change, and analyzes innovative solutions and policy recommendations to address this challenge. Challenges of energy demand: Large and ultra-large-scale data centers consume huge power, comparable to the sum of hundreds of thousands of ordinary North American families, and emerging AI ultra-large-scale centers consume dozens of times more power than this. In the first eight months of 2024, Microsoft, Meta, Google and Amazon have invested approximately US$125 billion in the construction and operation of AI data centers (JP Morgan, 2024) (Table 1). Growing energy demand is both a challenge and an opportunity. According to Canary Media, the looming electricity

Generative AI is revolutionizing film and television production. Luma's Ray 2 model, as well as Runway's Gen-4, OpenAI's Sora, Google's Veo and other new models, are improving the quality of generated videos at an unprecedented speed. These models can easily create complex special effects and realistic scenes, even short video clips and camera-perceived motion effects have been achieved. While the manipulation and consistency of these tools still need to be improved, the speed of progress is amazing. Generative video is becoming an independent medium. Some models are good at animation production, while others are good at live-action images. It is worth noting that Adobe's Firefly and Moonvalley's Ma

ChatGPT user experience declines: is it a model degradation or user expectations? Recently, a large number of ChatGPT paid users have complained about their performance degradation, which has attracted widespread attention. Users reported slower responses to models, shorter answers, lack of help, and even more hallucinations. Some users expressed dissatisfaction on social media, pointing out that ChatGPT has become “too flattering” and tends to verify user views rather than provide critical feedback. This not only affects the user experience, but also brings actual losses to corporate customers, such as reduced productivity and waste of computing resources. Evidence of performance degradation Many users have reported significant degradation in ChatGPT performance, especially in older models such as GPT-4 (which will soon be discontinued from service at the end of this month). this


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
