model ensemble guide

本文详细介绍了模型融合技术在提高机器学习任务准确率方面的应用。从Kaggle竞赛的角度出发,探讨了如何通过投票融合、平均融合及堆叠泛化等方法整合多个模型预测结果。文章还分析了模型融合减少泛化误差的原因,并提供了多种融合方法及其效果对比。


http://mlwave.com/kaggle-ensembling-guide/

这里有很多非常好的博客。



Model ensembling is a very powerful technique to increase accuracy on a variety of ML tasks. In this article I will share my ensembling approaches for Kaggle Competitions.

For the first part we look at creating ensembles from submission files. The second part will look at creating ensembles through stacked generalization/blending.

I answer why ensembling reduces the generalization error. Finally I show different methods of ensembling, together with their results and code to try it out for yourself.

This is how you win ML competitions: you take other peoples’ work and ensemble them together.” Vitaly Kuznetsov NIPS2014

Creating ensembles from submission files

The most basic and convenient way to ensemble is to ensemble Kaggle submission CSV files. You only need the predictions on the test set for these methods — no need to retrain a model. This makes it a quick way to ensemble already existing model predictions, ideal when teaming up.

Voting ensembles.

We first take a look at a simple majority vote ensemble. Let’s see why model ensembling reduces error rate and why it works better to ensemble low-correlated model predictions.

Error correcting codes

During space missions it is very important that all signals are correctly relayed.

If we have a signal in the form of a binary string like:

1110110011101111011111011011

and somehow this signal is corrupted (a bit is flipped) to:

1010110011101111011111011011

then lives could be lost.

coding solution was found in error correcting codes. The simplest error correcting code is a repetition-code: Relay the signal multiple times in equally sized chunks and have a majority vote.

Original signal:
1110110011

Encoded:
10,3 101011001111101100111110110011

Decoding:
1010110011
1110110011
1110110011

Majority vote:
1110110011

Signal corruption is a very rare occurrence and often occur in small bursts. So then it figures that it is even rarer to have a corrupted majority vote.

As long as the corruption is not completely unpredictable (has a 50% chance of occurring) then signals can be repaired.

A machine learning example

Suppose we have a test set of 10 samples. The ground truth is all positive (“1”):

1111111111

We furthermore have 3 binary classifiers (A,B,C) with a 70% accuracy. You can view these classifiers for now as pseudo-random number generators which output a “1” 70% of the time and a “0” 30% of the time.

We will now show how these pseudo-classifiers are able to obtain 78% accuracy through a voting ensemble.

A pinch of maths

For a majority vote with 3 members we can expect 4 outcomes:

All three are correct
  0.7 * 0.7 * 0.7
= 0.3429

Two are correct
  0.7 * 0.7 * 0.3
+ 0.7 * 0.3 * 0.7
+ 0.3 * 0.7 * 0.7
= 0.4409

Two are wrong
  0.3 * 0.3 * 0.7
+ 0.3 * 0.7 * 0.3
+ 0.7 * 0.3 * 0.3
= 0.189

All three are wrong
  0.3 * 0.3 * 0.3
= 0.027

We see that most of the times (~44%) the majority vote corrects an error. This majority vote ensemble will be correct an average of ~78% (0.3429 + 0.4409 = 0.7838).

Number of voters

Like repetition codes increase in their error-correcting capability when more codes are repeated, so do ensembles usually improve when adding more ensemble members.

Repetition codes performance on graph

Using the same pinch of maths as above: a voting ensemble of 5 pseudo-random classifiers with 70% accuracy would be correct ~83% of the time. One or two errors are being corrected during ~66% of the majority votes. (0.36015 + 0.3087)

Correlation

When I first joined the team for KDD-cup 2014, Marios Michailidis (KazAnova) proposed something peculiar. He calculated the Pearson correlation for all our submission files and gathered a few well-performing models which were less correlated.

Creating an averaging ensemble from these diverse submissions gave us the biggest 50-spot jump on the leaderboard. Uncorrelated submissions clearly do better when ensembled than correlated submissions. But why?

To see this, let us take 3 simple models again. The ground truth is still all 1’s:

1111111100 = 80% accuracy
1111111100 = 80% accuracy
1011111100 = 70% accuracy.

These models are highly correlated in their predictions. When we take a majority vote we see no improvement:

1111111100 = 80% accuracy

Now we compare to 3 less-performing, but highly uncorrelated models:

1111111100 = 80% accuracy
0111011101 = 70% accuracy
1000101111 = 60% accuracy

When we ensemble this with a majority vote we get:

1111111101 = 90% accuracy

Which is an improvement: A lower correlation between ensemble model members seems to result in an increase in the error-correcting capability.

Use for Kaggle: Forest Cover Type prediction

ForestMajority votes make most sense when the evaluation metric requires hard predictions, for instance with (multiclass-) classification accuracy.

The forest cover type prediction challenge uses the UCI Forest CoverType dataset. The dataset has 54 attributes and there are 6 classes.

We create a simple starter model with a 500-tree Random Forest. We then create a few more models and pick the best performing one. For this task and our model selection an ExtraTreesClassifier works best.

Weighing

We then use a weighted majority vote. Why weighing? Usually we want to give a better model more weight in a vote. So in our case we count the vote by the best model 3 times. The other 4 models count for one vote each.

The reasoning is as follows: The only way for the inferior models to overrule the best model (expert) is for them to collectively (and confidently) agree on an alternative.

We can expect this ensemble to repair a few erroneous choices by the best model, leading to a small improvement only. That’s our punishment for forgoing a democracy and creating a Plato’s Republic.

“Every city encompasses two cities that are at war with each other.” Plato in The Republic

Table 1. shows the result of training 5 models, and the resulting score when combining these with a weighted majority vote.

MODEL PUBLIC ACCURACY SCORE
GradientBoostingMachine 0.65057
RandomForest Gini 0.75107
RandomForest Entropy 0.75222
ExtraTrees Entropy 0.75524
ExtraTrees Gini (Best) 0.75571
Voting Ensemble (Democracy) 0.75337
Voting Ensemble (3*Best vs. Rest) 0.75667
Use for Kaggle: CIFAR-10 Object detection in images

CIFAR-10CIFAR-10 is another multi-class classification challenge where accuracy matters.

Our team leader for this challenge, Phil Culliton, first found the best setup to replicate a good model from dr. Graham.

Then he used a voting ensemble of around 30 convnets submissions (all scoring above 90% accuracy). The best single model of the ensemble scored 0.93170.

A voting ensemble of 30 models scored 0.94120. A ~0.01 reduction in error rate, pushing the resulting score beyond the estimated human classification accuracy.

Code

We have a sample voting script you could use at the MLWave Github repo. It operates on a directory of Kaggle submissions and creates a new submission. Update: Armando Segnini has added weighing.

Ensembling. Train 10 neural networks and average their predictions. It’s a fairly trivial technique that results in easy, sizeable performance improvements.

One may be mystified as to why averaging helps so much, but there is a simple reason for the effectiveness of averaging. Suppose that two classifiers have an error rate of 70%. Then, when they agree they are right. But when they disagree, one of them is often right, so now the average prediction will place much more weight on the correct answer.

The effect will be especially strong whenever the network is confident when it’s right and unconfident when it’s wrong. Ilya Sutskever A brief overview of Deep Learning.

Averaging

Averaging works well for a wide range of problems (both classification and regression) and metrics (AUC, squared error or logaritmic loss).

There is not much more to averaging than taking the mean of individual model predictions. An often heard shorthand for this on Kaggle is “bagging submissions”.

Averaging predictions often reduces overfit. You ideally want a smooth separation between classes, and a single model’s predictions can be a little rough around the edges.

Learning from noise

The above image is from the Kaggle competition: Don’t Overfit!, the black line shows a better separation than the green line. The green line has learned from noisy datapoints. No worries! Averaging multiple different green lines should bring us closer to the black line.

Remember our goal is not to memorize the training data (there are far more efficient ways to store data than inside a random forest), but to generalize well to new unseen data.

Kaggle use: Bag of Words Meets Bags of Popcorn

IconsThis is a movie sentiment analysis contest. In a previous post we used an online perceptron script to get 95.2 AUC.

The perceptron is a decent linear classifier which is guaranteed to find a separation if the data is linearly separable. This is a welcome property to have, but you have to realize a perceptron stops learning once this separation is reached. It does not necessarily find the best separation for new data.

So what would happen if we initialize 5 perceptrons with random weights and combine their predictions through an average? Why, we get an improvement on the test set!

MODEL PUBLIC AUC SCORE
Perceptron 0.95288
Random Perceptron 0.95092
Random Perceptron 0.95128
Random Perceptron 0.95118
Random Perceptron 0.95072
Bagged Perceptrons 0.95427

Above results also illustrate that ensembling can (temporarily) save you from having to learn about the finer details and inner workings of a specific Machine Learning algorithm. If it works, great! If it doesn’t, not much harm done.

Perceptron bagging

You also won’t get a penalty for averaging 10 exactly the same linear regressions. Bagging a single poorly cross-validated and overfitted submission may even bring you some gain through adding diversity (thus less correlation).

Code

We have posted a simple averaging script on Github that takes as input a directory of .csv files and outputs an averaged submission. Update: Dat Le has added a geometric averaging script. Geometric mean can outperform a plain average.

Rank averaging

When averaging the outputs from multiple different models some problems can pop up. Not all predictors are perfectly calibrated: they may be over- or underconfident when predicting a low or high probability. Or the predictions clutter around a certain range.

In the extreme case you may have a submission which looks like this:

Id,Prediction
1,0.35000056
2,0.35000002
3,0.35000098
4,0.35000111

Such a prediction may do well on the leaderboard when the evaluation metric is ranking or threshold based like AUC. But when averaged with another model like:

Id,Prediction
1,0.57
2,0.04
3,0.96
4,0.99

it will not change the ensemble much at all.

Our solution is to first turn the predictions into ranks, then averaging these ranks.

Id,Rank,Prediction
1,1,0.35000056
2,0,0.35000002
3,2,0.35000098
4,3,0.35000111

After normalizing the averaged ranks between 0 and 1 you are sure to get an even distribution in your predictions. The resulting rank-averaged ensemble:

Id,Prediction
1,0.33
2,0.0
3,0.66
4,1.0
Historical ranks.

Ranking requires a test set. So what do you do when want predictions for a single new sample? You could rank it together with the old test set, but this will increase the complexity of your solution.

A solution is using historical ranks. Store the old test set predictions together with their rank. Now when you predict a new test sample like “0.35000110” you find the closest old prediction and take its historical rank (in this case rank “3” for “0.35000111”).

Kaggle use case: Acquire Valued Shoppers Challenge

ScissorsRanking averages do well on ranking and threshold-based metrics (like AUC) and search-engine quality metrics (like average precision at k).

The goal of the shopper challenge was to rank the chance that a shopper would become a repeat customer.

Our team first took an average of multiple Vowpal Wabbit models together with an R GLMNet model. Then we used a ranking average to improve the exact same ensemble.

MODEL PUBLIC PRIVATE
Vowpal Wabbit A 0.60764 0.59962
Vowpal Wabbit B 0.60737 0.59957
Vowpal Wabbit C 0.60757 0.59954
GLMNet 0.60433 0.59665
Average Bag 0.60795 0.60031
Rank average Bag 0.61027 0.60187

I already wrote about the Avito challenge where rank averaging gave us a hefty increase.

Finally, when weighted rank averaging the bagged perceptrons from the previous chapter (1x) with the new bag-of-words tutorial (3x) on fastML.com we improve that model’s performance from 0.96328 AUC to 0.96461 AUC.

Code

A simple work-horse rank averaging script is added to the MLWave Github repo.

Competitions are effective because there are any number of techniques that can be applied to any modeling problem, but we can’t know in advance which will be most effective. Anthony Goldbloom Data Prediction Competitions — Far More than Just a Bit of Fun

Whiskey blending

From ‘How Scotch Blended Whisky is Made’ on Youtube

Stacked Generalization & Blending

Averaging prediction files is nice and easy, but it’s not the only method that the top Kagglers are using. The serious gains start with stacking and blending. Hold on to your top-hats and petticoats: Here be dragons. With 7 heads. Standing on top of 30 other dragons.

Netflix

Netflix organized and popularized the first data science competitions. Competitors in the movie recommendation challenge really pushed the state of the art on ensemble creation, perhaps so much so that Netflix decided not to implement the winning solution in production. That one was simply too complex.

Nevertheless, a number of papers and novel methods resulted from this challenge:

All are interesting, accessible and relevant reads when you want to improve your Kaggle game.

Netflix Prize Leaderboard

This is a truly impressive compilation and culmination of years of work, blending hundreds of predictive models to finally cross the finish line. We evaluated some of the new methods offline but the additional accuracy gains that we measured did not seem to justify the engineering effort needed to bring them into a production environment. Netflix Engineers

Stacked generalization

Stacked generalization was introduced by Wolpert in a 1992 paper, 2 years before the seminal Breiman paper “Bagging Predictors“. Wolpert is famous for another very popular machine learning theorem: “There is no free lunch in search and optimization“.

The basic idea behind stacked generalization is to use a pool of base classifiers, then using another classifier to combine their predictions, with the aim of reducing the generalization error.

Let’s say you want to do 2-fold stacking:

  • Split the train set in 2 parts: train_a and train_b
  • Fit a first-stage model on train_a and create predictions for train_b
  • Fit the same model on train_b and create predictions for train_a
  • Finally fit the model on the entire train set and create predictions for the test set.
  • Now train a second-stage stacker model on the probabilities from the first-stage model(s).

A stacker model gets more information on the problem space by using the first-stage predictions as features, than if it was trained in isolation.

It is usually desirable that the level 0 generalizers are of all “types”, and not just simple variations of one another (e.g., we want surface-fitters, Turing-machine builders, statistical extrapolators, etc., etc.). In this way all possible ways of examining the learning set and trying to extrapolate from it are being exploited. This is part of what is meant by saying that the level 0 generalizers should “span the space”.

[…] stacked generalization is a means of non-linearly combining generalizers to make a new generalizer, to try to optimally integrate what each of the original generalizers has to say about the learning set. The more each generalizer has to say (which isn’t duplicated in what the other generalizer’s have to say), the better the resultant stacked generalization. Wolpert (1992) Stacked Generalization

Blending

Blending is a word introduced by the Netflix winners. It is very close to stacked generalization, but a bit simpler and less risk of an information leak. Some researchers use “stacked ensembling” and “blending” interchangeably.

With blending, instead of creating out-of-fold predictions for the train set, you create a small holdout set of say 10% of the train set. The stacker model then trains on this holdout set only.

Blending has a few benefits:

  • It is simpler than stacking.
  • It wards against an information leak: The generalizers and stackers use different data.
  • You do not need to share a seed for stratified folds with your teammates. Anyone can throw models in the ‘blender’ and the blender decides if it wants to keep that model or not.

The cons are:

  • You use less data overall
  • The final model may overfit to the holdout set.
  • Your CV is more solid with stacking (calculated over more folds) than using a single small holdout set.

As for performance, both techniques are able to give similar results, and it seems to be a matter of preference and skill which you prefer. I myself prefer stacking.

If you can not choose, you can always do both. Create stacked ensembles with stacked generalization and out-of-fold predictions. Then use a holdout set to further combine these models at a third stage.

Stacking with logistic regression

Stacking with logistic regression is one of the more basic and traditional ways of stacking. A script I found by Emanuele Olivettihelped me understand this.

When creating predictions for the test set, you can do that in one go, or take an average of the out-of-fold predictors. Though taking the average is the clean and more accurate way to do this, I still prefer to do it in one go as that slightly lowers both model and coding complexity.

Kaggle use: “Papirusy z Edhellond”

GondorI used the above blend.py script by Emanuele to compete in this inClass competition. Stacking 8 base models (diverse ET’s, RF’s and GBM’s) with Logistic Regression gave me my second best score of 0.99409 accuracy, good for first place.

Kaggle use: KDD-cup 2014

Using this script I was able to improve a model from Yan Xu. Her model before stacking scored ~0.605 AUC. With stacking this improved to ~0.625.

Stacking with non-linear algorithms

Popular non-linear algorithms for stacking are GBM, KNN, NN, RF and ET.

Non-linear stacking with the original features on multiclass problems gives surprising gains. Obviously the first-stage predictions are very informative and get the highest feature importance. Non-linear algorithms find useful interactions between the original features and the meta-model features.

Kaggle use: TUT Headpose Estimation Challenge

TUT headpose The TUT Headpose Estimation challenge can be treated as a multi-class multi-label classification challenge.

For every label a separate ensemble model was trained.

The following table shows the result of training individual models, and their improved scores when stacking the predicted class probabilities with an extremely randomized trees model.

MODEL PUBLIC MAE PRIVATE MAE
Random Forests 500 estimators 6.156 6.546
Extremely Randomized Trees 500 estimators 6.317 6.666
KNN-Classifier with 5 neighbors 6.828 7.460
Logistic Regression 6.694 6.949
Stacking with Extremely Randomized Trees 4.772 4.718

We see that stacked generalization with standard models is able to reduce the error by around 30%(!).

Read more about this result in the paper: Computer Vision for Head Pose Estimation: Review of a Competition.

Code

You can find a function to create out-of-fold probability predictionsin the MLWave Github repo. You could use numpy horizontal stacking (hstack) to create blended datasets.

Feature weighted linear stacking

Feature-weighted linear stacking stacks engineered meta-features together with model predictions. The hope is that the stacking model learns which base model is the best predictor for samples with a certain feature value. Linear algorithms are used to keep the resulting model fast and simple to inspect.

Blended prediction

Vowpal Wabbit can implement a form of feature-weighted linear stacking out of the box. If we have a train set like:

1 |f f_1:0.55 f_2:0.78 f_3:7.9 |s RF:0.95 ET:0.97 GBM:0.92

We can add quadratic feature interactions between the s-featurespace and the f-featurespace by adding -q fs. The features in the f-namespace can be engineered meta-features like in the paper, or they can be the original features.

Quadratic linear stacking of models

This did not have a name so I made one up. It is very similar to feature-weighted linear stacking, but it creates combinations of model predictions. This improved the score on numerous experiments, most noticeably on the Modeling Women’s Healthcare Decision competition on DrivenData.

Using the same VW training set as before:

1 |f f_1:0.55 f_2:0.78 f_3:7.9 |s RF:0.95 ET:0.97 GBM:0.92

We can train with -q ss creating quadratic feature interactions (RF*GBM) between the model predictions.

This can easily be combined with feature-weighted linear stacking: -q fs -q ss, possibly improving on both.

So now you have a case where many base models should be created. You don’t know apriori which of these models are going to be helpful in the final meta model. In the case of two stage models, it is highly likely weak base models are preferred.

So why tune these base models very much at all? Perhaps tuning here is just obtaining model diversity. But at the end of the day you don’t know which base models will be helpful. And the final stage will likely be linear (which requires no tuning, or perhaps a single parameter to give some sparsity).  Mike KimTuning doesn’t matter. Why are you doing it?

Stacking classifiers with regressors and vice versa

Stacking allows you to use classifiers for regression problems and vice versa. For instance, one may try a base model with quantile regression on a binary classification problem. A good stacker should be able to take information from the predictions, even though usually regression is not the best classifier.

Using classifiers for regression problems is a bit trickier. You use binning first: You turn the y-label into evenly spaced classes. A regression problem that requires you to predict wages can be turned into a multiclass classification problem like so:

  • Everything under 20k is class 1.
  • Everything between 20k and 40k is class 2.
  • Everything over 40k is class 3.

The predicted probabilities for these classes can help a stacking regressor make better predictions.

“I learned that you never, ever, EVER go anywhere without your out-of-fold predictions. If I go to Hawaii or to the bathroom I am bringing them with. Never know when I need to train a 2nd or 3rd level meta-classifier” T. Sharf

Stacking unsupervised learned features

There is no reason we are restricted to using supervised learning techniques with stacking. You can also stack with unsupervised learning techniques.

K-Means clustering is a popular technique that makes sense here. Sofia-ML implements a fast online k-means algorithm suitable for this.

Another more recent interesting addition is to use t-SNE: Reduce the dataset to 2 or 3 dimensions and stack this with a non-linear stacker. Using a holdout set for stacking/blending feels like the safest choice here. See here for a solution by Mike Kim, using t-SNE vectors and boosting them with XGBoost: ‘0.41599 via t-SNE meta-bagging‘.

t-SNE

Piotr shows a nice visualization with t-SNE on the Otto Product Classification Challenge data set.

Online Stacking

I spend quit a lot of time working out an idea I had for online stacking: first create small fully random trees from the hashed binary representation. Substract profit or add profit when the tree makes a correct prediction. Now take the most profitable and least profitable trees and add them to the feature representation.

It worked, but only on artificial data. For instance, a linear perceptron with online random tree stacking was able to learn a non-linear XOR-problem. It did not work on any real-life data I tried it on, and believe me, I tried. So from now on I’ll be suspicious of papers which only feature artificial data sets to showcase their new algorithm.

A similar idea did work for the author of the paper: random bit regression. Here many random linear functions are created from the features, and the best are found through heavy regularization. This I was able to replicate with success on some datasets. This will the topic of a future post.

A more concrete example of (semi-) online stacking is with ad click prediction. Models trained on recent data perform better there. So when a dataset has a temporal effect, you could use Vowpal Wabbit to train on the entire dataset, and use a more complex and powerful tool like XGBoost to train on the last day of data. Then you stack the XGBoost predictions together with the samples and let Vowpal Wabbit do what it does best: optimizing loss functions.

The natural world is complex, so it figures that ensembling different models can capture more of this complexity. Ben Hamner ‘Machine learning best practices we’ve learned from hundreds of competitions’ (video)

Everything is a hyper-parameter

When doing stacking/blending/meta-modeling it is healthy to think of every action as a hyper-parameter for the stacker model.

So for instance:

  • Not scaling the data
  • Standard-Scaling the data
  • Minmax scaling the data

are simply extra parameters to be tuned to improve the ensemble performance. Likewise, the number of base models to use can be seen as a parameter to optimize. Feature selection (top 70%) or imputation (impute missing features with a 0) are other examples of meta-parameters.

Like a random gridsearch is a good candidate for tuning algorithm parameters, so does it work for tuning these meta-parameters.

Sometimes it is useful to allow XGBoost to see what a KNN-classifier sees. – Marios Michailidis

Model Selection

You can further optimize scores by combining multiple ensembled models.

  • There is the ad-hoc approach: Use averaging, voting or rank averaging on manually-selected well-performing ensembles.
  • Greedy forward model selection (Caruana et al.). Start with a base ensemble of 3 or so good models. Add a model when it increases the train set score the most. By allowing put-back of models, a single model may be picked multiple times (weighing).
  • Genetic model selection uses genetic algorithms and CV-scores as the fitness function. See for instance inversion‘s solution ‘Strategy for top 25 position‘.
  • I use a fully random method inspired by Caruana’s method: Create a 100 or so ensembles from randomly selected ensembles (without placeback). Then pick the highest scoring model.

Automation

Otto GroupWhen stacking for the Otto product classification competition I quickly got a good top 10 spot. Adding more and more base models and bagging multiple stacked ensembles I was able to keep improving my score.

Once I had reached 7 base models stacked by 6 stackers, a sense of panic and gloom started to set in. Would I be able to replicate all of this? These complex and slow unwieldy models were out of my comfort zone of fast and simple Machine Learning.

I spend the rest of the competition building a way to automate stacking. For base models pure random algorithms with pure random parameters are trained. Wrappers were written to make classifiers like VW, Sofia-ML, RGF, MLP and XGBoost play nicely with the Scikit-learn API.

Whiteboard automated stacking
The first whiteboard sketch for a parallelized automated stacker with 3 buckets

For stackers I let the script use SVM, random forests, extremely randomized trees, GBM and XGBoost with random parameters and a random subset of base models.

Finally the created stackers are averaged when their fold-predictions on the train set produced a lower loss.

This automated stacker was able to rank 57th spot a week before the competition ended. It contributed to my final ensemble. The only difference was I never spend time tuning or selecting: I started the script, went to bed, and awoke to a good solution.

Otto Leaderboard

The automated stacker is able to get a top 10% score without any tuning or manual model selection on a competitive task with over 3000 competitors.

Automatic stacking is one of my new big interests. Expect a few follow-up articles on this. The best result of automatic stacking was found on the TUT Headpose Estimation challenge. This black-box solution beats the current state-of-the-art set by domain experts who created special-purpose algorithms for this particular problem.

Tut headpose leaderboard

Noteworthy: This was a multi-label classification problem. Predictions for both “yaw” and “pitch” were required. Since the “yaw” and “pitch”-labels of a head pose are interrelated, stacking a model with predictions for “yaw” increased the accuracy for “pitch” predictions and vice versa. An interesting result.

Models visualized as a network can be trained used back-propagation: then stacker models learn which base models reduce the error the most.

Ensemble Network

Next to CV-scores one could take the standard deviation of the CV-scores into account (a smaller deviation is a safer choice). One could look at optimizing complexity/memory usage and running times. Finally one can look at adding correlation into the mix — make the script prefer uncorrelated model predictions when creating ensembles.

The entire automated stacking pipeline can be parallelized and distributed. This also brings speed improvements and faster good results on a single laptop.

Contextual bandit optimization seems like a good alternative to fully random gridsearch: We want our algorithm to start exploiting good parameters and models and remember that the random SVM it picked last time ran out of memory. These additions to stacking will be explored in greater detail soon.

In the meantime you can get a sneak preview on the MLWave Github repo: “Hodor-autoML“.

The #1 and #2 winners of the Otto product classification challenge used ensembles of over a 1000 different models. Read more about the first place and the second place.

Why create these Frankenstein ensembles?

You may wonder why this exercise in futility: stacking and combining 1000s of models and computational hours is insanity right? Well… yes. But these monster ensembles still have their uses:

  • You can win Kaggle competitions.
  • You can beat most state-of-the-art academic benchmarks with a single approach.
  • You can then compare your new-and-improved benchmark with the performance of a simpler, more production-friendly model
  • One day, today’s computers and clouds will seem weak. You’ll be ready.
  • It is possible to transfer knowledge from the ensemble back to a simpler shallow model (Hinton’s Dark Knowledge, Caruana’sModel Compression)
  • Not all base models necessarily need to finish in time. In that regard, ensembling introduces a form of graceful degradation: loss of one model is not fatal for creating good predictions.
  • Automated large ensembles ward against overfit and add a form of regularization, without requiring much tuning or selection. In principle stacking could be used by lay-people.
  • It is currently one of the best methods to improve machine learning algorithms, perhaps telling use something about efficienthuman ensemble learning.
  • A 1% increase in accuracy may push an investment fund from making a loss, into making a little less loss. More seriously: Improving healthcare screening methods helps save lives.

Update: Thanks a lot to Dat Le for documenting and refactoring thecode accompanying this article. Thanks to Armando Segnini for adding weighted averaging. Thanks a lot everyone for the encouraging comments. My apologies if I have forgotten to link to your previous inspirational work. Further reading at “More is always better – The power of Simple Ensembles” by Carter Sibley, “Tradeshift Benchmark Tutorial with two-stage SKLearn models” by Dmitry Dryomov, “Stacking, Blending and Stacked Generalization” by Eric ChioEnsemble Learning: The wisdom of the crowds (of machines) by Lior Rokach, and “Deep Support Vector Machines” by Marco Wiering.

Terminology: When I say ensembling I mean ‘model averaging’: combining multiple models. Algorithms like Random Forests use ensembling techniques like bagging internally. For this article we are not interested in that.

The intro image came from WikiMedia Commons and is in the public domain, courtesy of Jesse Merz.


# -*- coding: utf-8 -*- """ 京东高价值客户识别与全链路行为预测系统 作者:李梓翀 李富生 数据来源:京东公开数据(模拟生成) """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from datetime import datetime, timedelta import random import time import os from faker import Faker from sklearn.preprocessing import LabelEncoder, StandardScaler from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.cluster import KMeans from sklearn.metrics import (roc_auc_score, precision_score, recall_score, f1_score, mean_absolute_error, roc_curve) from sklearn.decomposition import PCA # -------------------------- # 数据爬取与模拟生成 # -------------------------- def generate_jd_simulation_data(num_users=5000, num_records=50000): """ 模拟生成京东用户行为数据 """ print("开始生成模拟京东数据...") fake = Faker('zh_CN') np.random.seed(42) # 创建用户基础数据 users = pd.DataFrame({ 'user_id': [f'U{str(i).zfill(6)}' for i in range(1, num_users+1)], 'age': np.random.randint(18, 65, num_users), 'gender': np.random.choice(['男', '女'], num_users, p=[0.55, 0.45]), 'city': [fake.city() for _ in range(num_users)], 'is_plus_member': np.random.choice([0, 1], num_users, p=[0.7, 0.3]), 'join_date': [fake.date_between(start_date='-3y', end_date='today') for _ in range(num_users)] }) # 创建行为数据 behavior_types = ['浏览', '加购', '购买', '评价', '收藏'] categories = { '家电': ['冰箱', '洗衣机', '空调', '电视', '微波炉'], '手机': ['智能手机', '配件', '平板', '智能手表'], '电脑': ['笔记本', '台式机', '显示器', '外设'], '数码': ['相机', '耳机', '音箱', '存储设备'], '家居': ['家具', '家纺', '厨具', '灯具'] } records = [] for _ in range(num_records): user_id = f'U{str(np.random.randint(1, num_users+1)).zfill(6)}' behavior_time = fake.date_time_between(start_date='-90d', end_date='now') # 随机选择品类和子类 main_cat = random.choice(list(categories.keys())) sub_cat = random.choice(categories[main_cat]) # 行为类型概率分布 behavior_prob = [0.5, 0.2, 0.15, 0.1, 0.05] behavior_type = np.random.choice(behavior_types, p=behavior_prob) # 订单相关数据 order_amount = 0 if behavior_type == '购买': # 高价商品概率 if main_cat == '家电' and np.random.random() < 0.3: order_amount = np.random.uniform(3000, 20000) else: order_amount = np.random.uniform(100, 3000) # 促销活动参与 is_promotion = 1 if np.random.random() < 0.4 else 0 # 物流评分 delivery_rating = np.random.randint(3, 6) if behavior_type == '购买' else 0 records.append({ 'user_id': user_id, 'behavior_time': behavior_time, 'behavior_type': behavior_type, 'main_category': main_cat, 'sub_category': sub_cat, 'order_amount': order_amount, 'is_promotion': is_promotion, 'delivery_rating': delivery_rating }) # 创建DataFrame df = pd.DataFrame(records) # 添加未来行为标签(模拟未来3个月行为) print("添加未来行为标签...") user_purchase_future = df[df['behavior_type'] == '购买'].groupby('user_id')['order_amount'].sum().reset_index() # 修正语法错误:括号匹配 user_purchase_future['will_buy_high_end'] = np.where( (user_purchase_future['order_amount'] > 5000) & (np.random.random(len(user_purchase_future)) > 0.3), 1, 0) # PLUS会员续费倾向 - 修正语法错误 plus_users = users[users['is_plus_member'] == 1]['user_id'].tolist() user_purchase_future['will_renew_plus'] = np.where( user_purchase_future['user_id'].isin(plus_users), np.random.choice([0, 1], len(user_purchase_future)), 0) # 合并数据 df = pd.merge(df, users, on='user_id', how='left') df = pd.merge(df, user_purchase_future[['user_id', 'will_buy_high_end', 'will_renew_plus']], on='user_id', how='left').fillna(0) # 保存数据 os.makedirs('data', exist_ok=True) df.to_csv('data/jd_simulated_data.csv', index=False) print(f"模拟数据生成完成,共 {len(df)} 条记录,保存至 data/jd_simulated_data.csv") return df # -------------------------- # 数据预处理 # -------------------------- def preprocess_data(df): """数据预处理与特征工程""" print("\n开始数据预处理与特征工程...") # 1. 数据清洗 # 过滤异常订单(金额异常) df = df[df['order_amount'] <= 50000] # 修复时间戳错误(示例:修复未来时间戳) current_date = datetime.now() df = df[df['behavior_time'] <= current_date] # 2. 特征工程 - 基础特征 # 计算用户活跃天数(最近90天) active_days = df.groupby('user_id')['behavior_time'].apply( lambda x: x.dt.date.nunique()).reset_index(name='active_days') # 促销敏感度(参与促销活动比例) promo_sensitivity = df[df['is_promotion'] == 1].groupby('user_id').size().reset_index(name='promo_count') total_actions = df.groupby('user_id').size().reset_index(name='total_actions') promo_sensitivity = pd.merge(promo_sensitivity, total_actions, on='user_id') promo_sensitivity['promo_sensitivity'] = promo_sensitivity['promo_count'] / promo_sensitivity['total_actions'] # 品类浏览集中度 category_concentration = df.groupby(['user_id', 'main_category']).size().reset_index(name='category_count') category_concentration = category_concentration.groupby('user_id')['category_count'].apply( lambda x: (x.max() / x.sum())).reset_index(name='category_concentration') # 3. 高价值客户标签定义 high_value_criteria = df.groupby('user_id').agg( total_spend=('order_amount', 'sum'), purchase_count=('behavior_type', lambda x: (x == '购买').sum()), category_count=('main_category', 'nunique') ).reset_index() high_value_criteria['is_high_value'] = np.where( (high_value_criteria['total_spend'] > 5000) | (high_value_criteria['purchase_count'] > 8) | (high_value_criteria['category_count'] >= 3), 1, 0) # 4. 合并特征 features = pd.merge(active_days, promo_sensitivity[['user_id', 'promo_sensitivity']], on='user_id') features = pd.merge(features, category_concentration, on='user_id') features = pd.merge(features, high_value_criteria[['user_id', 'is_high_value']], on='user_id') # 5. 添加用户基本信息 user_base = df[['user_id', 'age', 'gender', 'city', 'is_plus_member', 'join_date']].drop_duplicates() features = pd.merge(features, user_base, on='user_id') # 6. 添加时间相关特征 df['last_activity'] = df.groupby('user_id')['behavior_time'].transform('max') features['last_activity_gap'] = (datetime.now() - features['join_date']).dt.days # 7. 添加行为统计特征 behavior_counts = pd.crosstab(df['user_id'], df['behavior_type']).reset_index() features = pd.merge(features, behavior_counts, on='user_id') # 8. 品类偏好特征 for cat in ['家电', '手机', '电脑', '数码', '家居']: cat_users = df[df['main_category'] == cat]['user_id'].unique() features[f'prefers_{cat}'] = np.where(features['user_id'].isin(cat_users), 1, 0) print(f"特征工程完成,共生成 {len(features.columns)} 个特征") return features # -------------------------- # 探索性数据分析 (EDA) # -------------------------- def perform_eda(df, features): """执行探索性数据分析""" print("\n开始探索性数据分析...") # 设置绘图风格 sns.set_style("whitegrid") plt.figure(figsize=(18, 12)) # 1. 用户行为类型分布 plt.subplot(2, 2, 1) behavior_counts = df['behavior_type'].value_counts() sns.barplot(x=behavior_counts.index, y=behavior_counts.values, palette="viridis") plt.title('用户行为类型分布') plt.ylabel('数量') # 2. PLUS会员与非会员客单价对比 plt.subplot(2, 2, 2) purchase_df = df[df['behavior_type'] == '购买'] sns.boxplot(x='is_plus_member', y='order_amount', data=purchase_df, palette="Set2") plt.title('PLUS会员 vs 非会员客单价对比') plt.xlabel('PLUS会员') plt.ylabel('订单金额') # 3. 物流评分与复购率关系 plt.subplot(2, 2, 3) # 计算复购率 repurchase_users = purchase_df.groupby('user_id').filter(lambda x: len(x) > 1)['user_id'].unique() purchase_df['is_repurchase'] = purchase_df['user_id'].isin(repurchase_users).astype(int) # 按物流评分分组计算复购率 delivery_repurchase = purchase_df.groupby('delivery_rating')['is_repurchase'].mean().reset_index() sns.lineplot(x='delivery_rating', y='is_repurchase', data=delivery_repurchase, marker='o', linewidth=2.5, color='darkorange') plt.title('物流评分对复购率的影响') plt.xlabel('物流评分') plt.ylabel('复购率') plt.ylim(0, 1) # 4. 高价值客户特征热力图 plt.subplot(2, 2, 4) corr_matrix = features[['active_days', 'promo_sensitivity', 'category_concentration', '购买', '加购', 'is_high_value']].corr() sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', fmt=".2f") plt.title('行为特征相关性') plt.tight_layout() plt.savefig('results/eda_results.png', dpi=300) plt.show() # 5. 高价值客户人口统计特征 plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) sns.countplot(x='gender', hue='is_high_value', data=features, palette="Set1") plt.title('高价值客户性别分布') plt.xlabel('性别') plt.ylabel('数量') plt.subplot(1, 2, 2) sns.boxplot(x='is_high_value', y='age', data=features, palette="Set2") plt.title('高价值客户年龄分布') plt.xlabel('是否高价值客户') plt.ylabel('年龄') plt.tight_layout() plt.savefig('results/high_value_demographics.png', dpi=300) plt.show() print("EDA分析完成,结果保存至 results/ 目录") # -------------------------- # 预测模型构建 # -------------------------- def build_prediction_models(features, target_column): """构建预测模型""" print(f"\n构建预测模型: {target_column}") # 1. 数据准备 # 选择特征 model_features = features.drop(['user_id', 'join_date', 'will_buy_high_end', 'will_renew_plus'], axis=1, errors='ignore') # 处理分类变量 categorical_cols = ['gender', 'city'] model_features = pd.get_dummies(model_features, columns=categorical_cols, drop_first=True) # 定义目标变量 y = features[target_column] # 2. 划分训练集/测试集 X_train, X_test, y_train, y_test = train_test_split( model_features, y, test_size=0.25, random_state=42, stratify=y) # 3. 模型初始化 models = { 'XGBoost': RandomForestClassifier( n_estimators=150, max_depth=8, min_samples_split=10, class_weight='balanced', random_state=42 ), '随机森林': RandomForestClassifier( n_estimators=150, max_depth=8, min_samples_split=10, class_weight='balanced', random_state=42 ), '逻辑回归': LogisticRegression( max_iter=1000, class_weight='balanced', penalty='l2', C=0.1, random_state=42, solver='liblinear' ) } # 4. 模型训练与评估 results = {} feature_importances = {} for name, model in models.items(): print(f"训练 {name} 模型...") start_time = time.time() model.fit(X_train, y_train) train_time = time.time() - start_time # 预测 y_pred = model.predict(X_test) y_proba = model.predict_proba(X_test)[:, 1] if hasattr(model, 'predict_proba') else [0]*len(y_test) # 关键指标计算 auc = roc_auc_score(y_test, y_proba) if len(np.unique(y_test)) > 1 else 0.5 precision = precision_score(y_test, y_pred, zero_division=0) recall = recall_score(y_test, y_pred, zero_division=0) f1 = f1_score(y_test, y_pred, zero_division=0) # 自定义加权MAE(高价商品权重更高) weights = np.where(features.loc[y_test.index, 'is_high_value'] == 1, 2.0, 1.0) mae = mean_absolute_error(y_test, y_proba, sample_weight=weights) if len(np.unique(y_test)) > 1 else 0 results[name] = { 'AUC': auc, '精确率': precision, '召回率': recall, 'F1分数': f1, '加权MAE': mae, '训练时间(秒)': train_time } # 保存重要特征 if hasattr(model, 'feature_importances_'): feat_imp = pd.Series(model.feature_importances_, index=X_train.columns) feature_importances[name] = feat_imp.sort_values(ascending=False) # 绘制ROC曲线 if len(np.unique(y_test)) > 1: plt.figure(figsize=(8, 6)) fpr, tpr, _ = roc_curve(y_test, y_proba) plt.plot(fpr, tpr, label=f'{name} (AUC = {auc:.2f})') plt.plot([0, 1], [0, 1], 'k--') plt.xlabel('假阳性率') plt.ylabel('真阳性率') plt.title(f'{target_column} ROC曲线') plt.legend() plt.savefig(f'results/{target_column}_{name}_roc_curve.png', dpi=300) plt.close() # 5. 特征重要性可视化 for model_name, imp in feature_importances.items(): plt.figure(figsize=(10, 8)) imp.head(15).sort_values().plot(kind='barh') plt.title(f'{model_name} - 特征重要性 (Top 15)') plt.tight_layout() plt.savefig(f'results/{target_column}_{model_name}_feature_importance.png', dpi=300) plt.close() return results, models # -------------------------- # 客户分群与画像 # -------------------------- def customer_segmentation(features): """客户分群与画像生成""" print("\n进行客户分群...") # 选择特征 cluster_features = features[[ 'active_days', 'promo_sensitivity', 'category_concentration', '浏览', '加购', '购买', 'age' ]] # 标准化 scaler = StandardScaler() X_cluster = scaler.fit_transform(cluster_features) # KMeans聚类 kmeans = KMeans(n_clusters=5, random_state=42, n_init=10) features['cluster'] = kmeans.fit_predict(X_cluster) # 分析群体特征 cluster_profiles = features.groupby('cluster').agg({ 'active_days': 'mean', 'promo_sensitivity': 'mean', 'category_concentration': 'mean', '浏览': 'mean', '加购': 'mean', '购买': 'mean', 'age': 'mean', 'is_high_value': 'mean', 'will_buy_high_end': 'mean', 'will_renew_plus': 'mean', 'is_plus_member': 'mean' }).reset_index() # 重命名集群 cluster_names = { 0: '低价值观望者', 1: '高价值忠诚客户', 2: '年轻活跃用户', 3: '促销敏感型用户', 4: '高消费低频用户' } cluster_profiles['cluster_name'] = cluster_profiles['cluster'].map(cluster_names) features['cluster_name'] = features['cluster'].map(cluster_names) # 可视化 - 群体价值分布 plt.figure(figsize=(10, 6)) sns.barplot(x='cluster_name', y='is_high_value', data=cluster_profiles, palette="viridis") plt.title('各客户群体高价值比例') plt.xlabel('客户群体') plt.ylabel('高价值客户比例') plt.xticks(rotation=15) plt.tight_layout() plt.savefig('results/cluster_high_value_distribution.png', dpi=300) plt.close() # 保存客户画像 cluster_profiles.to_csv('results/customer_cluster_profiles.csv', index=False) features.to_csv('results/customer_segmented_data.csv', index=False) print("客户分群完成,结果保存至 results/ 目录") return cluster_profiles # -------------------------- # 生成业务报告 # -------------------------- def generate_business_report(cluster_profiles, model_results): """生成业务策略报告""" print("\n生成业务策略报告...") report = """ # 京东高价值客户识别与行为预测分析报告 ## 1. 项目概述 本项目通过分析京东用户行为数据,构建高价值客户识别模型并预测其全链路行为。研究目标包括: - 建立高价值客户评估体系 - 预测高价商品购买概率(家电3C等) - 预测PLUS会员续费倾向 - 提出精准营销策略 ## 2. 关键发现 ### 2.1 高价值客户特征 - 高价值客户占比: {:.1f}% - 高价值客户主要特征: - 活跃天数比普通客户高{:.1f}倍 - 促销敏感度比普通客户高{:.1f}% - 跨品类消费比例比普通客户高{:.1f}倍 ### 2.2 客户群体分析 我们识别出5类典型客户群体: """.format( cluster_profiles['is_high_value'].mean() * 100, cluster_profiles[cluster_profiles['is_high_value'] > 0.5]['active_days'].mean() / cluster_profiles[cluster_profiles['is_high_value'] < 0.3]['active_days'].mean(), (cluster_profiles[cluster_profiles['is_high_value'] > 0.5]['promo_sensitivity'].mean() - cluster_profiles[cluster_profiles['is_high_value'] < 0.3]['promo_sensitivity'].mean()) * 100, cluster_profiles[cluster_profiles['is_high_value'] > 0.5]['category_concentration'].mean() / cluster_profiles[cluster_profiles['is_high_value'] < 0.3]['category_concentration'].mean() ) for _, row in cluster_profiles.iterrows(): report += "- **{}**: {:.1f}%为高价值客户,平均年龄{:.1f}岁,主要特征:{}\n".format( row['cluster_name'], row['is_high_value'] * 100, row['age'], get_cluster_description(row) ) report += "\n### 2.3 预测模型性能\n" # 高价商品购买预测结果 report += "**高价商品购买预测**:\n" for model, metrics in model_results['will_buy_high_end'].items(): report += ("- {}: AUC={:.3f}, 精确率={:.3f}, 召回率={:.3f}, " "F1={:.3f}\n").format( model, metrics['AUC'], metrics['精确率'], metrics['召回率'], metrics['F1分数']) # PLUS会员续费预测结果 report += "\n**PLUS会员续费预测**:\n" for model, metrics in model_results['will_renew_plus'].items(): report += ("- {}: AUC={:.3f}, 精确率={:.3f}, 召回率={:.3f}, " "F1={:.3f}\n").format( model, metrics['AUC'], metrics['精确率'], metrics['召回率'], metrics['F1分数']) report += """ ## 3. 业务建议 ### 3.1 高价值客户运营策略 - **高价值忠诚客户**: 提供专属客服、优先配送和限量商品访问权限 - **高消费低频用户**: 通过个性化推荐提高购买频率,推送高端新品 - **促销敏感型用户**: 定向发送优惠券和限时促销信息 ### 3.2 PLUS会员增长策略 - 针对高价值客户群体提供专属会员优惠 - 预测有流失风险的会员,提供续费激励 - 为新会员提供首单立减优惠 ### 3.3 家电3C品类增长策略 - 对高价商品潜在购买者提供分期免息服务 - 结合用户浏览行为推送相关配件和延保服务 - 针对跨品类用户提供组合优惠 ## 4. 实施计划 1. 部署预测模型到京东营销系统 2. 开发客户分群运营平台 3. 设计个性化营销活动 4. 建立效果监测指标体系 """ # 保存报告 os.makedirs('results', exist_ok=True) with open('results/business_report.md', 'w', encoding='utf-8') as f: f.write(report) print("业务报告生成完成,保存至 results/business_report.md") return report def get_cluster_description(row): """生成客户群体描述""" desc_map = { '低价值观望者': "浏览多购买少,促销敏感度低", '高价值忠诚客户': "高活跃、高消费、多品类购买", '年轻活跃用户': "活跃度高但消费水平中等", '促销敏感型用户': "对促销活动高度敏感,购买集中在促销期", '高消费低频用户': "购买频次低但单次消费金额高" } return desc_map.get(row['cluster_name'], "未知群体") # -------------------------- # 主执行流程 # -------------------------- if __name__ == "__main__": # 创建结果目录 os.makedirs('data', exist_ok=True) os.makedirs('results', exist_ok=True) # 生成模拟数据 if not os.path.exists('data/jd_simulated_data.csv'): df = generate_jd_simulation_data() else: df = pd.read_csv('data/jd_simulated_data.csv', parse_dates=['behavior_time']) print("加载现有模拟数据...") # 预处理与特征工程 features = preprocess_data(df) # 探索性数据分析 perform_eda(df, features) # 构建预测模型 model_results = {} high_end_results, high_end_models = build_prediction_models(features, 'will_buy_high_end') model_results['will_buy_high_end'] = high_end_results plus_renew_results, plus_models = build_prediction_models(features, 'will_renew_plus') model_results['will_renew_plus'] = plus_renew_results # 客户分群 cluster_profiles = customer_segmentation(features) # 生成业务报告 report = generate_business_report(cluster_profiles, model_results) print("\n" + "="*50) print("京东高价值客户分析完成!") print("="*50) print("结果文件:") print("- 原始数据: data/jd_simulated_data.csv") print("- 特征数据: results/customer_segmented_data.csv") print("- 客户画像: results/customer_cluster_profiles.csv") print("- 分析报告: results/business_report.md") print("- 可视化图表: results/ 目录下的图片文件") 这段代码报了如下的错误 Cell In[2], line 564 561 print("加载现有模拟数据...") 563 # 预处理与特征工程 --> 564 features = preprocess_data(df) 566 # 探索性数据分析 567 perform_eda(df, features) Cell In[2], line 180 178 # 6. 添加时间相关特征 179 df['last_activity'] = df.groupby('user_id')['behavior_time'].transform('max') --> 180 features['last_activity_gap'] = (datetime.now() - features['join_date']).dt.days 182 # 7. 添加行为统计特征 183 behavior_counts = pd.crosstab(df['user_id'], df['behavior_type']).reset_index() File c:\Users\lzc\anaconda3\envs\lzc\lib\site-packages\pandas\core\ops\common.py:72, in _unpack_zerodim_and_defer.<locals>.new_method(self, other) 68 return NotImplemented 70 other = item_from_zerodim(other) ---> 72 return method(self, other) File c:\Users\lzc\anaconda3\envs\lzc\lib\site-packages\pandas\core\arraylike.py:114, in OpsMixin.__rsub__(self, other) 112 @unpack_zerodim_and_defer("__rsub__") 113 def __rsub__(self, other): --> 114 return self._arith_method(other, roperator.rsub) ... File c:\Users\lzc\anaconda3\envs\lzc\lib\site-packages\pandas\core\roperator.py:15, in rsub(left, right) 14 def rsub(left, right): ---> 15 return right - left TypeError: unsupported operand type(s) for -: 'Timestamp' and 'datetime.date'这个报错是怎么回事,帮我改进一下
最新发布
06-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值