Category Archives: ML&DL

40 Interview Questions asked at Startups in Machine Learning / Data Science

Machine learning and data science are being looked as the drivers of the next industrial revolution happening in the world today. This also means that there are numerous exciting startups looking for data scientists.  What could be a better start for your aspiring career!

However, still, getting into these roles is not easy. You obviously need to get excited about the idea, team and the vision of the company. You might also find some real difficult techincal questions on your way. The set of questions asked depend on what does the startup do. Do they provide consulting? Do they build ML products ? You should always find this out prior to beginning your interview preparation.

To help you prepare for your next interview, I’ve prepared a list of 40 plausible & tricky questions which are likely to come across your way in interviews. If you can answer and understand these question, rest assured, you will give a tough fight in your job interview.

Note: A key to answer these questions is to have concrete practical understanding on ML and related statistical concepts.

40 interview questions asked at startups in machine learning

 

Interview Questions on Machine Learning

Q1. You are given a train data set having 1000 columns and 1 million rows. The data set is based on a classification problem. Your manager has asked you to reduce the dimension of this data so that model computation time can be reduced. Your machine has memory constraints. What would you do? (You are free to make practical assumptions.)

Answer: Processing a high dimensional data on a limited memory machine is a strenuous task, your interviewer would be fully aware of that. Following are the methods you can use to tackle such situation:

  1. Since we have lower RAM, we should close all other applications in our machine, including the web browser, so that most of the memory can be put to use.
  2. We can randomly sample the data set. This means, we can create a smaller data set, let’s say, having 1000 variables and 300000 rows and do the computations.
  3. To reduce dimensionality, we can separate the numerical and categorical variables and remove the correlated variables. For numerical variables, we’ll use correlation. For categorical variables, we’ll use chi-square test.
  4. Also, we can use PCA and pick the components which can explain the maximum variance in the data set.
  5. Using online learning algorithms like Vowpal Wabbit (available in Python) is a possible option.
  6. Building a linear model using Stochastic Gradient Descent is also helpful.
  7. We can also apply our business understanding to estimate which all predictors can impact the response variable. But, this is an intuitive approach, failing to identify useful predictors might result in significant loss of information.

Note: For point 4 & 5, make sure you read about online learning algorithms & Stochastic Gradient Descent. These are advanced methods.

Q2. Is rotation necessary in PCA? If yes, Why? What will happen if you don’t rotate the components?

Answer: Yes, rotation (orthogonal) is necessary because it maximizes the difference between variance captured by the component. This makes the components easier to interpret. Not to forget, that’s the motive of doing PCA where, we aim to select fewer components (than features) which can explain the maximum variance in the data set. By doing rotation, the relative location of the components doesn’t change, it only changes the actual coordinates of the points.

If we don’t rotate the components, the effect of PCA will diminish and we’ll have to select more number of components to explain variance in the data set.

Know more: PCA

 

Q3. You are given a data set. The data set has missing values which spread along 1 standard deviation from the median. What percentage of data would remain unaffected? Why?

Answer: This question has enough hints for you to start thinking! Since, the data is spread across median, let’s assume it’s a normal distribution. We know, in a normal distribution, ~68% of the data lies in 1 standard deviation from mean (or mode, median), which leaves ~32% of the data unaffected. Therefore, ~32% of the data would remain unaffected by missing values.

 

Q4. You are given a data set on cancer detection. You’ve build a classification model and achieved an accuracy of 96%. Why shouldn’t you be happy with your model performance? What can you do about it?

Answer: If you have worked on enough data sets, you should deduce that cancer detection results in imbalanced data. In an imbalanced data set, accuracy should not be used as a measure of performance because 96% (as given) might only be predicting majority class correctly, but our class of interest is minority class (4%) which is the people who actually got diagnosed with cancer. Hence, in order to evaluate model performance, we should use Sensitivity (True Positive Rate), Specificity (True Negative Rate), F measure to determine class wise performance of the classifier. If the minority class performance is found to to be poor, we can undertake the following steps:

  1. We can use undersampling, oversampling or SMOTE to make the data balanced.
  2. We can alter the prediction threshold value by doing probability caliberation and finding a optimal threshold using AUC-ROC curve.
  3. We can assign weight to classes such that the minority classes gets larger weight.
  4. We can also use anomaly detection.

Know more: Imbalanced Classification

 

Q5. Why is naive Bayes so ‘naive’ ?

Answer: naive Bayes is so ‘naive’ because it assumes that all of the features in a data set are equally important and independent. As we know, these assumption are rarely true in real world scenario.

 

Q6. Explain prior probability, likelihood and marginal likelihood in context of naiveBayes algorithm?

Answer: Prior probability is nothing but, the proportion of dependent (binary) variable in the data set. It is the closest guess you can make about a class, without any further information. For example: In a data set, the dependent variable is binary (1 and 0). The proportion of 1 (spam) is 70% and 0 (not spam) is 30%. Hence, we can estimate that there are 70% chances that any new email would  be classified as spam.

Likelihood is the probability of classifying a given observation as 1 in presence of some other variable. For example: The probability that the word ‘FREE’ is used in previous spam message is likelihood. Marginal likelihood is, the probability that the word ‘FREE’ is used in any message.

 

Q7. You are working on a time series data set. You manager has asked you to build a high accuracy model. You start with the decision tree algorithm, since you know it works fairly well on all kinds of data. Later, you tried a time series regression model and got higher accuracy than decision tree model. Can this happen? Why?

Answer: Time series data is known to posses linearity. On the other hand, a decision tree algorithm is known to work best to detect non – linear interactions. The reason why decision tree failed to provide robust predictions because it couldn’t map the linear relationship as good as a regression model did. Therefore, we learned that, a linear regression model can provide robust prediction given the data set satisfies its linearity assumptions.

 

Q8. You are assigned a new project which involves helping a food delivery company save more money. The problem is, company’s delivery team aren’t able to deliver food on time. As a result, their customers get unhappy. And, to keep them happy, they end up delivering food for free. Which machine learning algorithm can save them?

Answer: You might have started hopping through the list of ML algorithms in your mind. But, wait! Such questions are asked to test your machine learning fundamentals.

This is not a machine learning problem. This is a route optimization problem. A machine learning problem consist of three things:

  1. There exist a pattern.
  2. You cannot solve it mathematically (even by writing exponential equations).
  3. You have data on it.

Always look for these three factors to decide if machine learning is a tool to solve a particular problem.

 

Q9. You came to know that your model is suffering from low bias and high variance. Which algorithm should you use to tackle it? Why?

Answer:  Low bias occurs when the model’s predicted values are near to actual values. In other words, the model becomes flexible enough to mimic the training data distribution. While it sounds like great achievement, but not to forget, a flexible model has no generalization capabilities. It means, when this model is tested on an unseen data, it gives disappointing results.

In such situations, we can use bagging algorithm (like random forest) to tackle high variance problem. Bagging algorithms divides a data set into subsets made with repeated randomized sampling. Then, these samples are used to generate  a set of models using a single learning algorithm. Later, the model predictions are combined using voting (classification) or averaging (regression).

Also, to combat high variance, we can:

  1. Use regularization technique, where higher model coefficients get penalized, hence lowering model complexity.
  2. Use top n features from variable importance chart. May be, with all the variable in the data set, the algorithm is having difficulty in finding the meaningful signal.

 

Q10. You are given a data set. The data set contains many variables, some of which are highly correlated and you know about it. Your manager has asked you to run PCA. Would you remove correlated variables first? Why?

Answer: Chances are, you might be tempted to say No, but that would be incorrect. Discarding correlated variables have a substantial effect on PCA because, in presence of correlated variables, the variance explained by a particular component gets inflated.

For example: You have 3 variables in a data set, of which 2 are correlated. If you run PCA on this data set, the first principal component would exhibit twice the variance than it would exhibit with uncorrelated variables. Also, adding correlated variables lets PCA put more importance on those variable, which is misleading.

 

Q11. After spending several hours, you are now anxious to build a high accuracy model. As a result, you build 5 GBM models, thinking a boosting algorithm would do the magic. Unfortunately, neither of models could perform better than benchmark score. Finally, you decided to combine those models. Though, ensembled models are known to return high accuracy, but you are unfortunate. Where did you miss?

Answer: As we know, ensemble learners are based on the idea of combining weak learners to create strong learners. But, these learners provide superior result when the combined models are uncorrelated. Since, we have used 5 GBM models and got no accuracy improvement, suggests that the models are correlated. The problem with correlated models is, all the models provide same information.

For example: If model 1 has classified User1122 as 1, there are high chances model 2 and model 3 would have done the same, even if its actual value is 0. Therefore, ensemble learners are built on the premise of combining weak uncorrelated models to obtain better predictions.

 

Q12. How is kNN different from kmeans clustering?

Answer: Don’t get mislead by ‘k’ in their names. You should know that the fundamental difference between both these algorithms is, kmeans is unsupervised in nature and kNN is supervised in nature. kmeans is a clustering algorithm. kNN is a classification (or regression) algorithm.

kmeans algorithm partitions a data set into clusters such that a cluster formed is homogeneous and the points in each cluster are close to each other. The algorithm tries to maintain enough separability between these clusters. Due to unsupervised nature, the clusters have no labels.

kNN algorithm tries to classify an unlabeled observation based on its k (can be any number ) surrounding neighbors. It is also known as lazy learner because it involves minimal training of model. Hence, it doesn’t use training data to make generalization on unseen data set.

 

Q13. How is True Positive Rate and Recall related? Write the equation.

Answer: True Positive Rate = Recall. Yes, they are equal having the formula (TP/TP + FN).

Know more: Evaluation Metrics

 

Q14. You have built a multiple regression model. Your model R² isn’t as good as you wanted. For improvement, your remove the intercept term, your model R² becomes 0.8 from 0.3. Is it possible? How?

Answer: Yes, it is possible. We need to understand the significance of intercept term in a regression model. The intercept term shows model prediction without any independent variable i.e. mean prediction. The formula of R² = 1 – ∑(y – y´)²/∑(y – ymean)² where y´ is predicted value.   

When intercept term is present, R² value evaluates your model wrt. to the mean model. In absence of intercept term (ymean), the model can make no such evaluation, with large denominator, ∑(y - y´)²/∑(y)² equation’s value becomes smaller than actual, resulting in higher R².

 

Q15. After analyzing the model, your manager has informed that your regression model is suffering from multicollinearity. How would you check if he’s true? Without losing any information, can you still build a better model?

Answer: To check multicollinearity, we can create a correlation matrix to identify & remove variables having correlation above 75% (deciding a threshold is subjective). In addition, we can use calculate VIF (variance inflation factor) to check the presence of multicollinearity. VIF value <= 4 suggests no multicollinearity whereas a value of >= 10 implies serious multicollinearity. Also, we can use tolerance as an indicator of multicollinearity.

But, removing correlated variables might lead to loss of information. In order to retain those variables, we can use penalized regression models like ridge or lasso regression. Also, we can add some random noise in correlated variable so that the variables become different from each other. But, adding noise might affect the prediction accuracy, hence this approach should be carefully used.

Know more: Regression

 

Q16. When is Ridge regression favorable over Lasso regression?

Answer: You can quote ISLR’s authors Hastie, Tibshirani who asserted that, in presence of few variables with medium / large sized effect, use lasso regression. In presence of many variables with small / medium sized effect, use ridge regression.

Conceptually, we can say, lasso regression (L1) does both variable selection and parameter shrinkage, whereas Ridge regression only does parameter shrinkage and end up including all the coefficients in the model. In presence of correlated variables, ridge regression might be the preferred choice. Also, ridge regression works best in situations where the least square estimates have higher variance. Therefore, it depends on our model objective.

Know more: Ridge and Lasso Regression

 

Q17. Rise in global average temperature led to decrease in number of pirates around the world. Does that mean that decrease in number of pirates caused the climate change?

Answer: After reading this question, you should have understood that this is a classic case of “causation and correlation”. No, we can’t conclude that decrease in number of pirates caused the climate change because there might be other factors (lurking or confounding variables) influencing this phenomenon.

Therefore, there might be a correlation between global average temperature and number of pirates, but based on this information we can’t say that pirated died because of rise in global average temperature.

Know more: Causation and Correlation

 

Q18. While working on a data set, how do you select important variables? Explain your methods.

Answer: Following are the methods of variable selection you can use:

  1. Remove the correlated variables prior to selecting important variables
  2. Use linear regression and select variables based on p values
  3. Use Forward Selection, Backward Selection, Stepwise Selection
  4. Use Random Forest, Xgboost and plot variable importance chart
  5. Use Lasso Regression
  6. Measure information gain for the available set of features and select top n features accordingly.

 

Q19. What is the difference between covariance and correlation?

Answer: Correlation is the standardized form of covariance.

Covariances are difficult to compare. For example: if we calculate the covariances of salary ($) and age (years), we’ll get different covariances which can’t be compared because of having unequal scales. To combat such situation, we calculate correlation to get a value between -1 and 1, irrespective of their respective scale.

 

Q20. Is it possible capture the correlation between continuous and categorical variable? If yes, how?

Answer: Yes, we can use ANCOVA (analysis of covariance) technique to capture association between continuous and categorical variables.

 

Q21. Both being tree based algorithm, how is random forest different from Gradient boosting algorithm (GBM)?

Answer: The fundamental difference is, random forest uses bagging technique to make predictions. GBM uses boosting techniques to make predictions.

In bagging technique, a data set is divided into n samples using randomized sampling. Then, using a single learning algorithm a model is build on all samples. Later, the resultant predictions are combined using voting or averaging. Bagging is done is parallel. In boosting, after the first round of predictions, the algorithm weighs misclassified predictions higher, such that they can be corrected in the succeeding round. This sequential process of giving higher weights to misclassified predictions continue until a stopping criterion is reached.

Random forest improves model accuracy by reducing variance (mainly). The trees grown are uncorrelated to maximize the decrease in variance. On the other hand, GBM improves accuracy my reducing both bias and variance in a model.

Know more: Tree based modeling

 

Q22. Running a binary classification tree algorithm is the easy part. Do you know how does a tree splitting takes place i.e. how does the tree decide which variable to split at the root node and succeeding nodes?

Answer: A classification trees makes decision based on Gini Index and Node Entropy. In simple words, the tree algorithm find the best possible feature which can divide the data set into purest possible children nodes.

Gini index says, if we select two items from a population at random then they must be of same class and probability for this is 1 if population is pure. We can calculate Gini as following:

  1. Calculate Gini for sub-nodes, using formula sum of square of probability for success and failure (p^2+q^2).
  2. Calculate Gini for split using weighted Gini score of each node of that split

Entropy is the measure of impurity as given by (for binary class):

Entropy, Decision Tree

Here p and q is probability of success and failure respectively in that node. Entropy is zero when a node is homogeneous. It is maximum when a both the classes are present in a node at 50% – 50%.  Lower entropy is desirable.

 

Q23. You’ve built a random forest model with 10000 trees. You got delighted after getting training error as 0.00. But, the validation error is 34.23. What is going on? Haven’t you trained your model perfectly?

Answer: The model has overfitted. Training error 0.00 means the classifier has mimiced the training data patterns to an extent, that they are not available in the unseen data. Hence, when this classifier was run on unseen sample, it couldn’t find those patterns and returned prediction with higher error. In random forest, it happens when we use larger number of trees than necessary. Hence, to avoid these situation, we should tune number of trees using cross validation.

 

Q24. You’ve got a data set to work having p (no. of variable) > n (no. of observation). Why is OLS as bad option to work with? Which techniques would be best to use? Why?

Answer: In such high dimensional data sets, we can’t use classical regression techniques, since their assumptions tend to fail. When p > n, we can no longer calculate a unique least square coefficient estimate, the variances become infinite, so OLS cannot be used at all.

To combat this situation, we can use penalized regression methods like lasso, LARS, ridge which can shrink the coefficients to reduce variance. Precisely, ridge regression works best in situations where the least square estimates have higher variance.

Among other methods include subset regression, forward stepwise regression.

 

11222Q25. What is convex hull ? (Hint: Think SVM)

Answer: In case of linearly separable data, convex hull represents the outer boundaries of the two group of data points. Once convex hull is created, we get maximum margin hyperplane (MMH) as a perpendicular bisector between two convex hulls. MMH is the line which attempts to create greatest separation between two groups.

 

Q26. We know that one hot encoding increasing the dimensionality of a data set. But, label encoding doesn’t. How ?

Answer: Don’t get baffled at this question. It’s a simple question asking the difference between the two.

Using one hot encoding, the dimensionality (a.k.a features) in a data set get increased because it creates a new variable for each level present in categorical variables. For example: let’s say we have a variable ‘color’. The variable has 3 levels namely Red, Blue and Green. One hot encoding ‘color’ variable will generate three new variables as Color.Red, Color.Blue and Color.Green containing 0 and 1 value.

In label encoding, the levels of a categorical variables gets encoded as 0 and 1, so no new variable is created. Label encoding is majorly used for binary variables.

 

Q27. What cross validation technique would you use on time series data set? Is it k-fold or LOOCV?

Answer: Neither.

In time series problem, k fold can be troublesome because there might be some pattern in year 4 or 5 which is not in year 3. Resampling the data set will separate these trends, and we might end up validation on past years, which is incorrect. Instead, we can use forward chaining strategy with 5 fold as shown below:

  • fold 1 : training [1], test [2]
  • fold 2 : training [1 2], test [3]
  • fold 3 : training [1 2 3], test [4]
  • fold 4 : training [1 2 3 4], test [5]
  • fold 5 : training [1 2 3 4 5], test [6]

where 1,2,3,4,5,6 represents “year”.

 

Q28. You are given a data set consisting of variables having more than 30% missing values? Let’s say, out of 50 variables, 8 variables have missing values higher than 30%. How will you deal with them?

Answer: We can deal with them in the following ways:

  1. Assign a unique category to missing values, who knows the missing values might decipher some trend
  2. We can remove them blatantly.
  3. Or, we can sensibly check their distribution with the target variable, and if found any pattern we’ll keep those missing values and assign them a new category while removing others.

 

29. ‘People who bought this, also bought…’ recommendations seen on amazon is a result of which algorithm?

Answer: The basic idea for this kind of recommendation engine comes from collaborative filtering.

Collaborative Filtering algorithm considers “User Behavior” for recommending items. They exploit behavior of other users and items in terms of transaction history, ratings, selection and purchase information. Other users behaviour and preferences over the items are used to recommend items to the new users. In this case, features of the items are not known.

Know more: Recommender System

 

Q30. What do you understand by Type I vs Type II error ?

Answer: Type I error is committed when the null hypothesis is true and we reject it, also known as a ‘False Positive’. Type II error is committed when the null hypothesis is false and we accept it, also known as ‘False Negative’.

In the context of confusion matrix, we can say Type I error occurs when we classify a value as positive (1) when it is actually negative (0). Type II error occurs when we classify a value as negative (0) when it is actually positive(1).

 

Q31. You are working on a classification problem. For validation purposes, you’ve randomly sampled the training data set into train and validation. You are confident that your model will work incredibly well on unseen data since your validation accuracy is high. However, you get shocked after getting poor test accuracy. What went wrong?

Answer: In case of classification problem, we should always use stratified sampling instead of random sampling. A random sampling doesn’t takes into consideration the proportion of target classes. On the contrary, stratified sampling helps to maintain the distribution of target variable in the resultant distributed samples also.

 

Q32. You have been asked to evaluate a regression model based on R², adjusted R² and tolerance. What will be your criteria?

Answer: Tolerance (1 / VIF) is used as an indicator of multicollinearity. It is an indicator of percent of variance in a predictor which cannot be accounted by other predictors. Large values of tolerance is desirable.

We will consider adjusted R² as opposed to R² to evaluate model fit because R² increases irrespective of improvement in prediction accuracy as we add more variables. But, adjusted R² would only increase if an additional variable improves the accuracy of model, otherwise stays same. It is difficult to commit a general threshold value for adjusted R² because it varies between data sets. For example: a gene mutation data set might result in lower adjusted R² and still provide fairly good predictions, as compared to a stock market data where lower adjusted R² implies that model is not good.

 

Q33. In k-means or kNN, we use euclidean distance to calculate the distance between nearest neighbors. Why not manhattan distance ?

Answer: We don’t use manhattan distance because it calculates distance horizontally or vertically only. It has dimension restrictions. On the other hand, euclidean metric can be used in any space to calculate distance. Since, the data points can be present in any dimension, euclidean distance is a more viable option.

Example: Think of a chess board, the movement made by a bishop or a rook is calculated by manhattan distance because of their respective vertical & horizontal movements.

 

Q34. Explain machine learning to me like a 5 year old.

Answer: It’s simple. It’s just like how babies learn to walk. Every time they fall down, they learn (unconsciously) & realize that their legs should be straight and not in a bend position. The next time they fall down, they feel pain. They cry. But, they learn ‘not to stand like that again’. In order to avoid that pain, they try harder. To succeed, they even seek support from the door or wall or anything near them, which helps them stand firm.

This is how a machine works & develops intuition from its environment.

Note: The interview is only trying to test if have the ability of explain complex concepts in simple terms.

 

Q35. I know that a linear regression model is generally evaluated using Adjusted R² or F value. How would you evaluate a logistic regression model?

Answer: We can use the following methods:

  1. Since logistic regression is used to predict probabilities, we can use AUC-ROC curve along with confusion matrix to determine its performance.
  2. Also, the analogous metric of adjusted R² in logistic regression is AIC. AIC is the measure of fit which penalizes model for the number of model coefficients. Therefore, we always prefer model with minimum AIC value.
  3. Null Deviance indicates the response predicted by a model with nothing but an intercept. Lower the value, better the model. Residual deviance indicates the response predicted by a model on adding independent variables. Lower the value, better the model.

Know more: Logistic Regression

 

Q36. Considering the long list of machine learning algorithm, given a data set, how do you decide which one to use?

Answer: You should say, the choice of machine learning algorithm solely depends of the type of data. If you are given a data set which is exhibits linearity, then linear regression would be the best algorithm to use. If you given to work on images, audios, then neural network would help you to build a robust model.

If the data comprises of non linear interactions, then a boosting or bagging algorithm should be the choice. If the business requirement is to build a model which can be deployed, then we’ll use regression or a decision tree model (easy to interpret and explain) instead of black box algorithms like SVM, GBM etc.

In short, there is no one master algorithm for all situations. We must be scrupulous enough to understand which algorithm to use.

 

Q37. Do you suggest that treating a categorical variable as continuous variable would result in a better predictive model?

Answer: For better predictions, categorical variable can be considered as a continuous variable only when the variable is ordinal in nature.

 

Q38. When does regularization becomes necessary in Machine Learning?

Answer: Regularization becomes necessary when the model begins to ovefit / underfit. This technique introduces a cost term for bringing in more features with the objective function. Hence, it tries to push the coefficients for many variables to zero and hence reduce cost term. This helps to reduce model complexity so that the model can become better at predicting (generalizing).

 

Q39. What do you understand by Bias Variance trade off?

Answer:  The error emerging from any model can be broken down into three components mathematically. Following are these component :

error of a model

Bias error is useful to quantify how much on an average are the predicted values different from the actual value. A high bias error means we have a under-performing model which keeps on missing important trends. Variance on the other side quantifies how are the prediction made on same observation different from each other. A high variance model will over-fit on your training population and perform badly on any observation beyond training.

 

Q40. OLS is to linear regression. Maximum likelihood is to logistic regression. Explain the statement.

Answer: OLS and Maximum likelihood are the methods used by the respective regression methods to approximate the unknown parameter (coefficient) value. In simple words,

Ordinary least square(OLS) is a method used in linear regression which approximates the parameters resulting in minimum distance between actual and predicted values. Maximum Likelihood helps in choosing the the values of parameters which maximizes the likelihood that the parameters are most likely to produce observed data.

 

End Notes

You might have been able to answer all the questions, but the real value is in understanding them and generalizing your knowledge on similar questions. If you have struggled at these questions, no worries, now is the time to learn and not perform. You should right now focus on learning these topics scrupulously.

These questions are meant to give you a wide exposure on the types of questions asked at startups in machine learning. I’m sure these questions would leave you curious enough to do deeper topic research at your end. If you are planning for it, that’s a good sign.

Did you like reading this article? Have you appeared in any startup interview recently for data scientist profile? Do share your experience in comments below. I’d love to know your experience.

from:https://www.analyticsvidhya.com/blog/2016/09/40-interview-questions-asked-at-startups-in-machine-learning-data-science/

Android+TensorFlow+CNN+MNIST 手写数字识别实现

Catalogue

  1. 1. Overview
  2. 2. Practice
    1. 2.1. Environment
    2. 2.2. Train & Evaluate(Python+TensorFlow)
    3. 2.3. Test(Android+TensorFlow)
  3. 3. Theory
    1. 3.1. MNIST
    2. 3.2. CNN(Convolutional Neural Network)
      1. 3.2.1. CNN Keys
      2. 3.2.2. CNN Architecture
    3. 3.3. Regression + Softmax
      1. 3.3.1. Linear Regression
      2. 3.3.2. Softmax Regression
  4. 4. References & Recommends

Overview

本文系“SkySeraph AI 实践到理论系列”第一篇,咱以AI界的HelloWord 经典MNIST数据集为基础,在Android平台,基于TensorFlow,实现CNN的手写数字识别。
Code~


Practice

Environment

  • TensorFlow: 1.2.0
  • Python: 3.6
  • Python IDE: PyCharm 2017.2
  • Android IDE: Android Studio 3.0

Train & Evaluate(Python+TensorFlow)

训练和评估部分主要目的是生成用于测试用的pb文件,其保存了利用TensorFlow python API构建训练后的网络拓扑结构和参数信息,实现方式有很多种,除了cnn外还可以使用rnn,fcnn等。
其中基于cnn的函数也有两套,分别为tf.layers.conv2d和tf.nn.conv2d, tf.layers.conv2d使用tf.nn.conv2d作为后端处理,参数上filters是整数,filter是4维张量。原型如下:
convolutional.py文件
def conv2d(inputs, filters, kernel_size, strides=(1, 1), padding=’valid’, data_format=’channels_last’,
dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer=None,
bias_initializer=init_ops.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None,
activity_regularizer=None, kernel_constraint=None, bias_constraint=None, trainable=True, name=None,
reuse=None)

gen_nn_ops.py 文件

def conv2d(input, filter, strides, padding, use_cudnn_on_gpu=True, data_format="NHWC", name=None)

官方Demo实例中使用的是layers module,结构如下:

  • Convolutional Layer #1:32个5×5的filter,使用ReLU激活函数
  • Pooling Layer #1:2×2的filter做max pooling,步长为2
  • Convolutional Layer #2:64个5×5的filter,使用ReLU激活函数
  • Pooling Layer #2:2×2的filter做max pooling,步长为2
  • Dense Layer #1:1024个神经元,使用ReLU激活函数,dropout率0.4 (为了避免过拟合,在训练的时候,40%的神经元会被随机去掉)
  • Dense Layer #2 (Logits Layer):10个神经元,每个神经元对应一个类别(0-9)

核心代码在cnn_model_fn(features, labels, mode)函数中,完成卷积结构的完整定义,核心代码如下.

也可以采用传统的tf.nn.conv2d函数, 核心代码如下。

Test(Android+TensorFlow)

  • 核心是使用API接口: TensorFlowInferenceInterface.java
  • 配置gradle 或者 自编译TensorFlow源码导入jar和so
    compile ‘org.tensorflow:tensorflow-android:1.2.0’
  • 导入pb文件.pb文件放assets目录,然后读取

    String actualFilename = labelFilename.split(“file:///android_asset/“)[1];
    Log.i(TAG, “Reading labels from: “ + actualFilename);
    BufferedReader br = null;
    br = new BufferedReader(new InputStreamReader(assetManager.open(actualFilename)));
    String line;
    while ((line = br.readLine()) != null) {
    c.labels.add(line);
    }
    br.close();

  • TensorFlow接口使用
  • 最终效果:

Theory

MNIST

MNIST,最经典的机器学习模型之一,包含0~9的数字,28*28大小的单色灰度手写数字图片数据库,其中共60,000 training examples和10,000 test examples。
文件目录如下,主要包括4个二进制文件,分别为训练和测试图片及Label。

如下为训练图片的二进制结构,在真实数据前(pixel),有部分描述字段(魔数,图片个数,图片行数和列数),真实数据的存储采用大端规则。
(大端规则,就是数据的高字节保存在低内存地址中,低字节保存在高内存地址中)

在具体实验使用,需要提取真实数据,可采用专门用于处理字节的库struct中的unpack_from方法,核心方法如下:
struct.unpack_from(self._fourBytes2, buf, index)

MNIST作为AI的Hello World入门实例数据,TensorFlow封装对其封装好了函数,可直接使用
mnist = input_data.read_data_sets(‘MNIST’, one_hot=True)

CNN(Convolutional Neural Network)

CNN Keys

  • CNN,Convolutional Neural Network,中文全称卷积神经网络,即所谓的卷积网(ConvNets)。
  • 卷积(Convolution)可谓是现代深度学习中最最重要的概念了,它是一种数学运算,读者可以从下面链接[23]中卷积相关数学机理,包括分别从傅里叶变换和狄拉克δ函数中推到卷积定义,我们可以从字面上宏观粗鲁的理解成将因子翻转相乘卷起来。
  • 卷积动画。演示如下图[26],更多动画演示可参考[27]
  • 神经网络。一个由大量神经元(neurons)组成的系统,如下图所示[21]

    其中x表示输入向量,w为权重,b为偏值bias,f为激活函数。
  • Activation Function 激活函数: 常用的非线性激活函数有Sigmoid、tanh、ReLU等等,公式如下如所示。
    • Sigmoid缺点
      • 函数饱和使梯度消失(神经元在值为 0 或 1 的时候接近饱和,这些区域,梯度几乎为 0)
      • sigmoid 函数不是关于原点中心对称的(无0中心化)
    • tanh: 存在饱和问题,但它的输出是零中心的,因此实际中 tanh 比 sigmoid 更受欢迎。
    • ReLU
      • 优点1:ReLU 对于 SGD 的收敛有巨大的加速作用
      • 优点2:只需要一个阈值就可以得到激活值,而不用去算一大堆复杂的(指数)运算
      • 缺点:需要合理设置学习率(learning rate),防止训练时dead,还可以使用Leaky ReLU/PReLU/Maxout等代替
  • Pooling池化。一般分为平均池化mean pooling和最大池化max pooling,如下图所示[21]为max pooling,除此之外,还有重叠池化(OverlappingPooling)[24],空金字塔池化(Spatial Pyramid Pooling)[25]
    • 平均池化:计算图像区域的平均值作为该区域池化后的值。
    • 最大池化:选图像区域的最大值作为该区域池化后的值。

CNN Architecture

  • 三层神经网络。分别为输入层(Input layer),输出层(Output layer),隐藏层(Hidden layer),如下图所示[21]
  • CNN层级结构。 斯坦福cs231n中阐述了一种[INPUT-CONV-RELU-POOL-FC],如下图所示[21],分别为输入层,卷积层,激励层,池化层,全连接层。
  • CNN通用架构分为如下三层结构:
    • Convolutional layers 卷积层
    • Pooling layers 汇聚层
    • Dense (fully connected) layers 全连接层
  • 动画演示。参考[22]。

Regression + Softmax

机器学习有监督学习(supervised learning)中两大算法分别是分类算法和回归算法,分类算法用于离散型分布预测,回归算法用于连续型分布预测。
回归的目的就是建立一个回归方程用来预测目标值,回归的求解就是求这个回归方程的回归系数。
其中回归(Regression)算法包括Linear Regression,Logistic Regression等, Softmax Regression是其中一种用于解决多分类(multi-class classification)问题的Logistic回归算法的推广,经典实例就是在MNIST手写数字分类上的应用。

Linear Regression

Linear Regression是机器学习中最基础的模型,其目标是用预测结果尽可能地拟合目标label

  • 多元线性回归模型定义
  • 多元线性回归求解
  • Mean Square Error (MSE)
    • Gradient Descent(梯度下降法)
    • Normal Equation(普通最小二乘法)
    • 局部加权线性回归(LocallyWeightedLinearRegression, LWLR ):针对线性回归中模型欠拟合现象,在估计中引入一些偏差以便降低预测的均方误差。
    • 岭回归(ridge regression)和缩减方法
  • 选择: Normal Equation相比Gradient Descent,计算量大(需计算X的转置与逆矩阵),只适用于特征个数小于100000时使用;当特征数量大于100000时使用梯度法。当X不可逆时可替代方法为岭回归算法。LWLR方法增加了计算量,因为它对每个点做预测时都必须使用整个数据集,而不是计算出回归系数得到回归方程后代入计算即可,一般不选择。
  • 调优: 平衡预测偏差和模型方差(高偏差就是欠拟合,高方差就是过拟合)
    • 获取更多的训练样本 – 解决高方差
    • 尝试使用更少的特征的集合 – 解决高方差
    • 尝试获得其他特征 – 解决高偏差
    • 尝试添加多项组合特征 – 解决高偏差
    • 尝试减小 λ – 解决高偏差
    • 尝试增加 λ -解决高方差

Softmax Regression

  • Softmax Regression估值函数(hypothesis)
  • Softmax Regression代价函数(cost function)
  • 理解:
  • Softmax Regression & Logistic Regression:
    • 多分类 & 二分类。Logistic Regression为K=2时的Softmax Regression
    • 针对K类问题,当类别之间互斥时可采用Softmax Regression,当非斥时,可采用K个独立的Logistic Regression
  • 总结: Softmax Regression适用于类别数量大于2的分类,本例中用于判断每张图属于每个数字的概率。

References & Recommends

MNIST

Softmax

CNN

TensorFlow+CNN / TensorFlow+Android



By SkySeraph-2018

SkySeraph cnBlogs
SkySeraph CSDN

本文首发于skyseraph.com“Android+TensorFlow+CNN+MNIST 手写数字识别实现”

2017年度盘点:15个最流行的GitHub机器学习项目

在本文中,作者列出了 2017 年 GitHub 平台上最为热门的知识库,囊括了数据科学、机器学习、深度学习中的各种项目,希望能对大家学习、使用有所帮助。另,小编恬不知耻地把机器之心的 Github 项目也加了进来,求 star,求 pull requests。

GitHub 是计算机科学领域最为活跃的社区,在 GitHub 上,来自不同背景的人们分享越来越多的软件工具和资源库。在其中,你不仅可以获取自己所需的工具,还可以观看代码是如何写成并实现的。

作为一名机器学习爱好者,作者在本文中列出了 2017 年 GitHub 平台上最为热门的知识库,其中包含了学习资料与工具。希望对你的学习和研究有所帮助。

目录

1. 学习资源

1. Awesome Data Science

2. Machine Learning / Deep Learning Cheat Sheet

3. Oxford Deep Natural Language Processing Course Lectures

4. PyTorch – Tutorial

5. Resources of NIPS 2017

2. 开源工具

1. TensorFlow

2. TuriCreate – A Simplified Machine Learning Library

3. OpenPose

4. DeepSpeech

5. Mobile Deep Learning

6. Visdom

7. Deep Photo Style Transfer

8. CycleGAN

9. Seq2seq

10. Pix2code

3. 机器之心项目

1. AI00-百家影响人工智能未来的公司

2. Artificial-Intelligence-Terminology

3. ML-Tutorial-Experiment

1. 学习资源

1.1 Awesome Data Science

项目地址: https://github.com/bulutyazilim/awesome-datascience

该 repo 是数据科学的基本资源。多年来的无数贡献构建了此 repo 里面的各种资源,从入门指导、信息图,到社交网络上你需要 follow 的账号。无论你是初学者还是业内老兵,里面都有大量的资源需要学习。

从该 repo 的目录可以看出其深度。

1.2 Machine Learning / Deep Learning Cheat Sheet

项目地址:https://github.com/kailashahirwar/cheatsheets-ai

该项目以 cheatsheet 的形式介绍了机器学习/深度学习中常用的工具与技术,从 pandas 这样的简单工具到深度学习技术都涵盖其中。在收藏或者 fork 该项目之后,你就不用再费事搜索常用的技巧和注意事项了。

简单介绍下,cheatsheets 类型包括 pandas、numpy、scikit learn、matplotlib、ggplot、dplyr、tidyr、pySpark 和神经网络。

1.3 Oxford Deep Natural Language Processing Course Lectures

项目地址:https://github.com/oxford-cs-deepnlp-2017/lectures

斯坦福的 NLP 课程一直是自然语言处理领域的金牌教程。但是近期随着深度学习的发展,在 RNN 和 LSTM 等深度学习架构的帮助下,NLP 出现了大量进步。

该 repo 基于牛津大学的 NLP 课程,涵盖先进技术和术语,如使用 RNN 进行语言建模、语音识别、文本转语音(TTS)等。该 repo 包含该课程从课程材料到实践联系的所有内容。

1.4 PyTorch – Tutorial

项目地址:https://github.com/yunjey/pytorch-tutorial

截至今天,PyTorch 仍是 TensorFlow 的唯一竞争对手,它的功能和声誉使其成为了颇具竞争力的深度学习框架。因其 Pythonic 风格的编程、动态计算图和更快的原型开发,Pytorch 已经获得了深度学习社区的广泛关注。

该知识库包含 PyTorch 上大量的深度学习任务代码,包括 RNN、GAN 和神经风格迁移。其中的大多数模型在实现上仅需 30 余行代码。这充分说明了 PyTorch 的抽象能力,它让研究人员可以专注于找到正确的模型,而无需纠缠于编程语言和工具选择等细节。

1.5 Resources of NIPS 2017

项目地址:https://github.com/hindupuravinash/nips2017

该 repo 包含 NIPS 2017 的资源和所有受邀演讲、教程和研讨会的幻灯片。NIPS 是一年一度的机器学习和计算神经科学会议。

过去几年中,数据科学领域内的大部分突破性研究都曾作为研究结果出现在 NIPS 大会上。如果你想站在领域前沿,那这就是很好的资源!

2. 开源软件库

2.1 TensorFlow

项目地址:https://github.com/tensorflow/tensorflow

TensorFlow 是一种采用数据流图(data flow graph)进行数值计算的开源软件库。其中 Tensor 代表传递的数据为张量(多维数组),Flow 代表使用计算图进行运算。数据流图用「结点」(node)和「边」(edge)组成的有向图来描述数学运算。「结点」一般用来表示施加的数学操作,但也可以表示数据输入的起点和输出的终点,或者是读取/写入持久变量(persistent variable)的终点。边表示结点之间的输入/输出关系。这些数据边可以传送维度可动态调整的多维数据数组,即张量(tensor)。

TensorFlow 自正式发布以来,一直保持着「深度学习/机器学习」顶尖库的位置。谷歌大脑团队和机器学习社区也一直在积极地贡献并保持最新的进展,尤其是在深度学习领域。

TensorFlow 最初是使用数据流图进行数值计算的开源软件库,但从目前来看,它已经成为构建深度学习模型的完整框架。它目前主要支持 TensorFlow,但也支持 C、C++ 和 Java 等语言。此外,今年 11 月谷歌终于发布了新工具的开发者预览版本,这是一款 TensorFlow 用于移动设备和嵌入式设备的轻量级解决方案。

2.2 TuriCreate:一个简化的机器学习库

项目地址:https://github.com/apple/turicreate

TuriCreate 是苹果最近贡献的一个开源项目,它为机器学习模型提供易于使用的创建方法和部署方法,这些机器学习模型包括目标检测、人体姿势识别和推荐系统等复杂任务。

可能我们作为机器学习爱好者会比较熟悉 GraphLab Create,一个非常简便高效的机器学习库,而当初创建该库的公司 TuriCreate 被苹果收购时,造成了很大反响。

TuriCreate 是针对 Python 开发的,且它最强的的特征是将机器学习模型部署到 Core ML 中,用于开发 iOS、macOS、watchOS 和 tvOS 等应用程序。

2.3 OpenPose

项目地址: https://github.com/CMU-Perceptual-Computing-Lab/openpose

OpenPose 是一个多人关键点检测库,它可以帮助我们实时地检测图像或视频中某个人的位置。

OpenPose 软件库由 CMU 的感知计算实验室开发并维护,对于说明开源研究如何快速应用于部署到工业中,它是非常好的一个案例。

OpenPose 的一个使用案例是帮助解决活动检测问题,即演员完成的动作或活动能被实时捕捉到。然后这些关键点和它们的动作可用来制作动画片。OpenPose 不仅有 C++的 API 以使开发者能快速地访问它,同时它还有简单的命令行界面用来处理图像或视频。

2.4 DeepSpeech

项目地址: https://github.com/mozilla/DeepSpeech

DeepSpeech 是百度开发的开源实现库,它提供了当前顶尖的语音转文本合成技术。它基于 TensorFlow 和 Python,但也可以绑定到 NodeJS 或使用命令行运行。

Mozilla 一直是构建 DeepSpeech 和开源软件库的主要研究力量,Mozilla 技术战略副总裁 Sean White 在一篇博文中写道:「目前只有少数商用质量的语音识别引擎是开源的,它们大多数由大型公司主宰。这样就减少了初创公司、研究人员和传统企业为它们的用户定制特定的产品与服务。但我们与机器学习社区的众多开发者和研究者共同完善了该开源库,因此目前 DeepSpeech 已经使用了复杂和前沿的机器学习技术创建语音到文本的引擎。」

2.5 Mobile Deep Learning

项目地址:https://github.com/baidu/mobile-deep-learning

该 repo 将数据科学中的当前最佳技术移植到了移动平台上。该 repo 由百度研究院开发,目的是将深度学习模型以低复杂性和高速度部署到移动设备(例如 Android 和 IOS)上。

该 repo 解释了一个简单的用例,即目标检测。它可以识别目标(例如一张图像中的手机)的准确位置,很棒不是吗?

2.6 Visdom

项目地址:https://github.com/facebookresearch/visdom

Visdom 支持图表、图像和文本在协作者之间进行传播。你可以用编程的方式组织可视化空间,或者通过 UI 为实时数据创建仪表盘,检查实验结果,或者调试实验代码。

绘图函数中的输入会发生改变,尽管大部分输入是数据的张量 X(而非数据本身)和(可选)张量 Y(包含可选数据变量,如标签或时间戳)。它支持所有基本图表类型,以创建 Plotly 支持的可视化。

Visdom 支持使用 PyTorch 和 Numpy。

2.7 Deep Photo Style Transfer

项目地址:https://github.com/luanfujun/deep-photo-styletransfer

该 repo 基于近期论文《Deep Photo Style Transfer》,该论文介绍了一种用于摄影风格迁移的深度学习方法,可处理大量图像内容,同时有效迁移参考风格。该方法成功克服了失真,满足了大量场景中的摄影风格迁移需求,包括时间、天气、季节、艺术编辑等场景。

2.8 CycleGAN

项目地址:https://github.com/junyanz/CycleGAN

CycleGAN 是一个有趣且强大的库,展现了该顶尖技术的潜力。举例来说,下图大致展示了该库的能力:调整图像景深。这里有趣的点在于你事先并没有告诉算法需要注意图像的哪一部分。算法完全依靠自己做到了!

目前该库用 Lua 编写,但是它也可以在命令行中使用。

2.9 Seq2seq

项目地址:https://github.com/google/seq2seq

Seq2seq 最初是为机器翻译而建立的,但已经被开发用于多种其它任务,包括摘要生成、对话建模和图像捕捉。只要一个问题的结构是将输入数据编码为一种格式,并将其解码为另一种格式,就可以使用 Seq2seq 框架。它使用了所有流行的基于 Python 的 TensorFlow 库进行编程。

2.10 Pix2code

项目地址:https://github.com/tonybeltramelli/pix2code

这个深度学习项目非常令人振奋,它尝试为给定的 GUI 自动生成代码。当建立网站或移动设备界面的时候,通常前端工程师必须编写大量枯燥的代码,这很费时和低效。这阻碍了开发者将主要的时间用于实现真正的功能和软件逻辑。Pix2code 的目的是通过将过程自动化来克服这一困难。它基于一种新方法,允许以单个 GUI 截图作为输入来生成计算机 token。

Pix2code 使用 Python 编写,可将移动设备和网站界面的捕捉图像转换成代码。

3. 机器之心项目

机器之心目前在 GitHub 上也有三个项目,分别是评估人工智能各领域优秀公司的 AI00、人工智能领域中英术语集和模型试验与解释项目。

3.1 AI00——机器之心百家影响人工智能未来的公司榜单

项目地址:https://github.com/jiqizhixin/AI00

人工智能是一个复杂庞大的体系,涉及众多学科,也关乎技术、产品、行业和资本等众多要素,本报告的写作团队只代表他们的专业观点,有自己的局限性,需要更多行业专家参与进来加以修正和完善。

我们深刻地理解在没有专业用户反馈的情况下所做出报告的质量局限性,所以希望用工程界「Agile Development」的理念来对待我们的报告,不断收集专业反馈来持续提升报告质量。

为此,我们将邀请人工智能领域的科学家、技术专家、产业专家、专业投资人和读者加入进来,共同完成这项人工智能的长期研究。我们将对参与者提供的信息进行汇总和整理,以月度为单位更新此份报告。

3.2 Artificial-Intelligence-Terminology

项目地址:https://github.com/jiqizhixin/Artificial-Intelligence-Terminology

我们将机器之心在编译技术文章和论文过程中所遇到的专业术语记录下来,希望有助于大家查阅和翻译(第二版)。

本词汇库目前拥有的专业词汇共计 760 个,主要为机器学习基础概念和术语,同时也是该项目的基本词汇。机器之心将继续完善术语的收录和扩展阅读的构建。

词汇更新主要分为两个阶段,第一阶段机器之心将继续完善基础词汇的构建,即通过权威教科书或其它有公信力的资料抽取常见术语。第二阶段机器之心将持续性地把编译论文或其他资料所出现的非常见术语更新到词汇表中。

读者的反馈意见和更新建议将贯穿整个阶段,并且我们将在项目致谢页中展示对该项目起积极作用的读者。因为我们希望术语的更新更具准确度和置信度,所以我们希望读者能附上该术语的来源地址与扩展地址。因此,我们能更客观地更新词汇,并附上可信的来源与扩展。

3.3 ML-Tutorial-Experiment

项目地址:https://github.com/jiqizhixin/ML-Tutorial-Experiment

该项目主要是展示我们在实验机器学习模型中所获得的经验与解释,目前我们解释并实现了卷积神经网络、生成对抗网络和 CapsNet。这些实现都有非常详细的文章以说明模型的结构与实现代码。如下所示为这三个实现项目的说明:

原文链接:https://www.analyticsvidhya.com/blog/2017/12/15-data-science-repositories-github-2017/

声明:本文由机器之心编译出品,原文来自Analytics Vidhya,转载请查看要求,机器之心对于违规侵权者保有法律追诉权。

from:https://www.jiqizhixin.com/articles/2017-12-21-10

一个框架解决几乎所有机器学习问题

周一个叫 Abhishek Thakur 的数据科学家,在他的 Linkedin 发表了一篇文章 Approaching (Almost) Any Machine Learning Problem,介绍他建立的一个自动的机器学习框架,几乎可以解决任何机器学习问题,项目很快也会发布出来。这篇文章迅速火遍 Kaggle,他参加过100多个数据科学相关的竞赛,积累了很多宝贵的经验,看他很幽默地说“写这样的框架需要很多丰富的经验,不是每个人都有这样的经历,而很多人有宝贵的经验,但是他们不愿意分享,我呢恰好是又有一些经验,又愿意分享的人”。当然这篇文章也是受到争议的,很多人觉得并不全面。

我最近也在准备参加 Kaggle,之前看过几个例子,自己也总结了一个分析的流程,今天看了这篇文章,里面提到了一些高效的方法,最干货的是,他做了一个表格,列出了各个算法通常需要训练的参数。

这个问题很重要,因为大部分时间都是通过调节参数,训练模型来提高精度。作为一个初学者,第一阶段,最想知道的问题,就是如何调节参数。因为分析的套路很简单,就那么几步,常用的算法也就那么几个,以为把算法调用一下就可以了么,那是肯定不行的。实际过程中,调用完算法后,结果一般都不怎么好,这个时候还需要进一步分析,哪些参数可以调优,哪些数据需要进一步处理,还有什么更合适的算法等等问题。

接下来一起来看一下他的框架。

据说数据科学家 60-70% 的时间都花在数据清洗和应用模型算法上面,这个框架主要针对算法的应用部分。

1507706111793_5442_1507706107871

Pipeline

什么是 Kaggle?

Kaggle是一个数据科学竞赛的平台,很多公司会发布一些接近真实业务的问题,吸引爱好数据科学的人来一起解决,可以通过这些数据积累经验,提高机器学习的水平。

应用算法解决 Kaggle 问题,一般有以下几个步骤:

  • 第一步:识别问题
  • 第二步:分离数据
  • 第三步:构造提取特征
  • 第四步:组合数据
  • 第五步:分解
  • 第六步:选择特征
  • 第七步:选择算法进行训练

当然,工欲善其事,必先利其器,要先把工具和包都安好。
最方便的就是安装 Anaconda,这里面包含大部分数据科学所需要的包,直接引入就可以了,常用的包有:

  • pandas:常用来将数据转化成 dataframe 形式进行操作
  • scikit-learn:里面有要用到的机器学习算法模型
  • matplotlib:用来画图
  • 以及 xgboost,keras,tqdm 等。

第一步:识别问题

在这一步先明确这个问题是分类还是回归。通过问题和数据就可以判断出来,数据由 X 和 label 列构成,label 可以一列也可以多列,可以是二进制也可以是实数,当它为二进制时,问题属于分类,当它为实数时,问题属于回归。

第二步:分离数据

1507706161329_2449_1507706157270

为什么需要将数据分成两部分?

用 Training Data 来训练模型,用 Validation Data 来检验这个模型的表现,不然的话,通过各种调节参数,模型可以在训练数据集上面表现的非常出色,但是这可能会是过拟合,过拟合就是太依赖现有的数据了,拟合的效果特别好,但是只适用于训练集,以致于来一个新的数据,就不知道该预测成什么了。所以需要有 Validation 来验证一下,看这个模型是在那里自娱自乐呢,还是真的表现出色。

在 scikit learn 包里就有工具可以帮你做到这些:
分类问题用 StrtifiedKFold

from sklearn.cross_validation import StratifiedKFold

回归问题用 KFold

from sklearn.cross_validation import KFold

第三步:构造特征

这个时候,需要将数据转化成模型需要的形式。数据有三种类型:数字,类别,文字。当数据是类别的形式时,需要将它的每一类提取出来作为单独一列,然后用二进制表示每条记录相应的值。例如:

record 1: 性别 女
record 2:性别 女
record 3:性别 男

转化之后就是:

         女 男
record 1: 1 0
record 2:1 0
record 3:0 1

这个过程 sklearn 也可以帮你做到:

from sklearn.preprocessing import LabelEncoder

或者

from sklearn.preprocessing import OneHotEncoder

第四步:组合数据

处理完 Feature 之后,就将它们组合到一起。
如果数据是稠密的,就可以用 numpy 的 hstack:

import numpy as np
X = np.hstack((x1, x2, ...))

如果是稀疏的,就用 sparse 的 hstack:

from scipy import sparse
X = sparse.hstack((x1, x2, ...))

组合之后,就可以应用以下算法模型:

  • RandomForestClassifier
  • RandomForestRegressor
  • ExtraTreesClassifier
  • ExtraTreesRegressor
  • XGBClassifier
  • XGBRegressor

但是不能应用线性模型,线性模型之前需要对数据进行正则化而不是上述预处理。

第五步:分解

这一步是为了进一步优化模型,可以用以下方法:

1507706259451_2054_1507706255470

PCA:Principal components analysis,主成分分析,是一种分析、简化数据集的技术。用于减少数据集的维数,同时保持数据集中的对方差贡献最大的特征。

from sklearn.decomposition import PCA

对于文字数据,在转化成稀疏矩阵之后,可以用 SVD

from sklearn.decomposition import TruncatedSVD

SVD:Singular Value Decomposition,奇异值分解,是线性代数中一种重要的矩阵分解,它总能找到标准化正交基后方差最大的维度,因此用它进行降维去噪。

第六步:选择特征

当特征个数越多时,分析特征、训练模型所需的时间就越长,容易引起“维度灾难”,模型也会越复杂,推广能力也会下降,所以需要剔除不相关或亢余的特征。

常用的算法有完全搜索,启发式搜索,和随机算法。

例如,Random Forest:

from sklearn.ensemble import RandomForestClassifier

或者 xgboost:

import xgboost as xgb

对于稀疏的数据,一个比较有名的方法是 chi-2:

from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2

第七步:选择算法进行训练

选择完最相关的参数之后,接下来就可以应用算法,常用的算法有:

Classification:
Random Forest
GBM
Logistic Regression
Naive Bayes
Support Vector Machines
k-Nearest Neighbors

Regression
Random Forest
GBM
Linear Regression
Ridge
Lasso
SVR

scikit-learn里可以看到分类和回归的可用的算法一览,包括它们的原理和例子代码。

在应用各算法之前先要明确这个方法到底是否合适。
为什么那么多算法里,只提出这几个算法呢,这就需要对比不同算法的性能了。
这篇神文 Do we Need Hundreds of Classifiers to Solve Real World Classification Problems 测试了179种分类模型在UCI所有的121个数据上的性能,发现Random Forests 和 SVM 性能最好。
我们可以学习一下里面的调研思路,看看是怎么样得到比较结果的,在我们的实践中也有一定的指导作用。

1507706339459_6332_1507706335760各算法比较

但是直接应用算法后,一般精度都不是很理想,这个时候需要调节参数,最干货的问题来了,什么模型需要调节什么参数呢?

1507706352167_4129_1507706348227

虽然在sklearn的文档里,会列出所有算法所带有的参数,但是里面并不会说调节哪个会有效。在一些mooc课程里,有一些项目的代码,里面可以看到一些算法应用时,他们重点调节的参数,但是有的也不会说清楚为什么不调节别的。这里作者根据他100多次比赛的经验,列出了这个表,我觉得可以借鉴一下,当然,如果有时间的话,去对照文档里的参数列表,再查一下算法的原理,通过理论也是可以判断出来哪个参数影响比较大的。

调参之后,也并不就是大功告成,这个时候还是需要去思考,是什么原因造成精度低的,是哪些数据的深意还没有被挖掘到,这个时候需要用统计和可视化去再一次探索数据,之后就再走一遍上面的过程。

我觉得这里还提到了很有用的一条经验是,把所有的 transformer 都保存起来,方便在 validation 数据集上面应用:

1507706374144_6119_1507706370146

文章里介绍了分析问题的思路,还提到了几条很实用的经验,不过经验终究是别人的经验,只能借鉴,要想提高自己的水平,还是要看到作者背后的事情,就是参加了100多次实战,接下来就去行动吧,享受用算法和代码与数据玩耍的兴奋吧。

from:https://cloud.tencent.com/community/article/440346

Data science Python notebooks

 

data-science-ipython-notebooks

Index

 

deep-learning

IPython Notebook(s) demonstrating deep learning functionality.

 

tensor-flow-tutorials

Additional TensorFlow tutorials:

Notebook Description
tsf-basics Learn basic operations in TensorFlow, a library for various kinds of perceptual and language understanding tasks from Google.
tsf-linear Implement linear regression in TensorFlow.
tsf-logistic Implement logistic regression in TensorFlow.
tsf-nn Implement nearest neighboars in TensorFlow.
tsf-alex Implement AlexNet in TensorFlow.
tsf-cnn Implement convolutional neural networks in TensorFlow.
tsf-mlp Implement multilayer perceptrons in TensorFlow.
tsf-rnn Implement recurrent neural networks in TensorFlow.
tsf-gpu Learn about basic multi-GPU computation in TensorFlow.
tsf-gviz Learn about graph visualization in TensorFlow.
tsf-lviz Learn about loss visualization in TensorFlow.

tensor-flow-exercises

Notebook Description
tsf-not-mnist Learn simple data curation by creating a pickle with formatted datasets for training, development and testing in TensorFlow.
tsf-fully-connected Progressively train deeper and more accurate models using logistic regression and neural networks in TensorFlow.
tsf-regularization Explore regularization techniques by training fully connected networks to classify notMNIST characters in TensorFlow.
tsf-convolutions Create convolutional neural networks in TensorFlow.
tsf-word2vec Train a skip-gram model over Text8 data in TensorFlow.
tsf-lstm Train a LSTM character model over Text8 data in TensorFlow.

 

theano-tutorials

Notebook Description
theano-intro Intro to Theano, which allows you to define, optimize, and evaluate mathematical expressions involving multi-dimensional arrays efficiently. It can use GPUs and perform efficient symbolic differentiation.
theano-scan Learn scans, a mechanism to perform loops in a Theano graph.
theano-logistic Implement logistic regression in Theano.
theano-rnn Implement recurrent neural networks in Theano.
theano-mlp Implement multilayer perceptrons in Theano.

 

keras-tutorials

Notebook Description
keras Keras is an open source neural network library written in Python. It is capable of running on top of either Tensorflow or Theano.
setup Learn about the tutorial goals and how to set up your Keras environment.
intro-deep-learning-ann Get an intro to deep learning with Keras and Artificial Neural Networks (ANN).
theano Learn about Theano by working with weights matrices and gradients.
keras-otto Learn about Keras by looking at the Kaggle Otto challenge.
ann-mnist Review a simple implementation of ANN for MNIST using Keras.
conv-nets Learn about Convolutional Neural Networks (CNNs) with Keras.
conv-net-1 Recognize handwritten digits from MNIST using Keras – Part 1.
conv-net-2 Recognize handwritten digits from MNIST using Keras – Part 2.
keras-models Use pre-trained models such as VGG16, VGG19, ResNet50, and Inception v3 with Keras.
auto-encoders Learn about Autoencoders with Keras.
rnn-lstm Learn about Recurrent Neural Networks (RNNs) with Keras.
lstm-sentence-gen Learn about RNNs using Long Short Term Memory (LSTM) networks with Keras.

deep-learning-misc

Notebook Description
deep-dream Caffe-based computer vision program which uses a convolutional neural network to find and enhance patterns in images.

 

scikit-learn

IPython Notebook(s) demonstrating scikit-learn functionality.

Notebook Description
intro Intro notebook to scikit-learn. Scikit-learn adds Python support for large, multi-dimensional arrays and matrices, along with a large library of high-level mathematical functions to operate on these arrays.
knn Implement k-nearest neighbors in scikit-learn.
linear-reg Implement linear regression in scikit-learn.
svm Implement support vector machine classifiers with and without kernels in scikit-learn.
random-forest Implement random forest classifiers and regressors in scikit-learn.
k-means Implement k-means clustering in scikit-learn.
pca Implement principal component analysis in scikit-learn.
gmm Implement Gaussian mixture models in scikit-learn.
validation Implement validation and model selection in scikit-learn.

 

statistical-inference-scipy

IPython Notebook(s) demonstrating statistical inference with SciPy functionality.

Notebook Description
scipy SciPy is a collection of mathematical algorithms and convenience functions built on the Numpy extension of Python. It adds significant power to the interactive Python session by providing the user with high-level commands and classes for manipulating and visualizing data.
effect-size Explore statistics that quantify effect size by analyzing the difference in height between men and women. Uses data from the Behavioral Risk Factor Surveillance System (BRFSS) to estimate the mean and standard deviation of height for adult women and men in the United States.
sampling Explore random sampling by analyzing the average weight of men and women in the United States using BRFSS data.
hypothesis Explore hypothesis testing by analyzing the difference of first-born babies compared with others.

 

pandas

IPython Notebook(s) demonstrating pandas functionality.

Notebook Description
pandas Software library written for data manipulation and analysis in Python. Offers data structures and operations for manipulating numerical tables and time series.
github-data-wrangling Learn how to load, clean, merge, and feature engineer by analyzing GitHub data from the Viz repo.
Introduction-to-Pandas Introduction to Pandas.
Introducing-Pandas-Objects Learn about Pandas objects.
Data Indexing and Selection Learn about data indexing and selection in Pandas.
Operations-in-Pandas Learn about operating on data in Pandas.
Missing-Values Learn about handling missing data in Pandas.
Hierarchical-Indexing Learn about hierarchical indexing in Pandas.
Concat-And-Append Learn about combining datasets: concat and append in Pandas.
Merge-and-Join Learn about combining datasets: merge and join in Pandas.
Aggregation-and-Grouping Learn about aggregation and grouping in Pandas.
Pivot-Tables Learn about pivot tables in Pandas.
Working-With-Strings Learn about vectorized string operations in Pandas.
Working-with-Time-Series Learn about working with time series in pandas.
Performance-Eval-and-Query Learn about high-performance Pandas: eval() and query() in Pandas.

 

matplotlib

IPython Notebook(s) demonstrating matplotlib functionality.

Notebook Description
matplotlib Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.
matplotlib-applied Apply matplotlib visualizations to Kaggle competitions for exploratory data analysis. Learn how to create bar plots, histograms, subplot2grid, normalized plots, scatter plots, subplots, and kernel density estimation plots.
Introduction-To-Matplotlib Introduction to Matplotlib.
Simple-Line-Plots Learn about simple line plots in Matplotlib.
Simple-Scatter-Plots Learn about simple scatter plots in Matplotlib.
Errorbars.ipynb Learn about visualizing errors in Matplotlib.
Density-and-Contour-Plots Learn about density and contour plots in Matplotlib.
Histograms-and-Binnings Learn about histograms, binnings, and density in Matplotlib.
Customizing-Legends Learn about customizing plot legends in Matplotlib.
Customizing-Colorbars Learn about customizing colorbars in Matplotlib.
Multiple-Subplots Learn about multiple subplots in Matplotlib.
Text-and-Annotation Learn about text and annotation in Matplotlib.
Customizing-Ticks Learn about customizing ticks in Matplotlib.
Settings-and-Stylesheets Learn about customizing Matplotlib: configurations and stylesheets.
Three-Dimensional-Plotting Learn about three-dimensional plotting in Matplotlib.
Geographic-Data-With-Basemap Learn about geographic data with basemap in Matplotlib.
Visualization-With-Seaborn Learn about visualization with Seaborn.

 

numpy

IPython Notebook(s) demonstrating NumPy functionality.

Notebook Description
numpy Adds Python support for large, multi-dimensional arrays and matrices, along with a large library of high-level mathematical functions to operate on these arrays.
Introduction-to-NumPy Introduction to NumPy.
Understanding-Data-Types Learn about data types in Python.
The-Basics-Of-NumPy-Arrays Learn about the basics of NumPy arrays.
Computation-on-arrays-ufuncs Learn about computations on NumPy arrays: universal functions.
Computation-on-arrays-aggregates Learn about aggregations: min, max, and everything in between in NumPy.
Computation-on-arrays-broadcasting Learn about computation on arrays: broadcasting in NumPy.
Boolean-Arrays-and-Masks Learn about comparisons, masks, and boolean logic in NumPy.
Fancy-Indexing Learn about fancy indexing in NumPy.
Sorting Learn about sorting arrays in NumPy.
Structured-Data-NumPy Learn about structured data: NumPy’s structured arrays.

 

python-data

IPython Notebook(s) demonstrating Python functionality geared towards data analysis.

Notebook Description
data structures Learn Python basics with tuples, lists, dicts, sets.
data structure utilities Learn Python operations such as slice, range, xrange, bisect, sort, sorted, reversed, enumerate, zip, list comprehensions.
functions Learn about more advanced Python features: Functions as objects, lambda functions, closures, *args, **kwargs currying, generators, generator expressions, itertools.
datetime Learn how to work with Python dates and times: datetime, strftime, strptime, timedelta.
logging Learn about Python logging with RotatingFileHandler and TimedRotatingFileHandler.
pdb Learn how to debug in Python with the interactive source code debugger.
unit tests Learn how to test in Python with Nose unit tests.

 

kaggle-and-business-analyses

IPython Notebook(s) used in kaggle competitions and business analyses.

Notebook Description
titanic Predict survival on the Titanic. Learn data cleaning, exploratory data analysis, and machine learning.
churn-analysis Predict customer churn. Exercise logistic regression, gradient boosting classifers, support vector machines, random forests, and k-nearest-neighbors. Includes discussions of confusion matrices, ROC plots, feature importances, prediction probabilities, and calibration/descrimination.

 

spark

IPython Notebook(s) demonstrating spark and HDFS functionality.

Notebook Description
spark In-memory cluster computing framework, up to 100 times faster for certain applications and is well suited for machine learning algorithms.
hdfs Reliably stores very large files across machines in a large cluster.

 

mapreduce-python

IPython Notebook(s) demonstrating Hadoop MapReduce with mrjob functionality.

Notebook Description
mapreduce-python Runs MapReduce jobs in Python, executing jobs locally or on Hadoop clusters. Demonstrates Hadoop Streaming in Python code with unit test and mrjob config file to analyze Amazon S3 bucket logs on Elastic MapReduce. Disco is another python-based alternative.

 

aws

IPython Notebook(s) demonstrating Amazon Web Services (AWS) and AWS tools functionality.

Also check out:

  • SAWS: A Supercharged AWS command line interface (CLI).
  • Awesome AWS: A curated list of libraries, open source repos, guides, blogs, and other resources.
Notebook Description
boto Official AWS SDK for Python.
s3cmd Interacts with S3 through the command line.
s3distcp Combines smaller files and aggregates them together by taking in a pattern and target file. S3DistCp can also be used to transfer large volumes of data from S3 to your Hadoop cluster.
s3-parallel-put Uploads multiple files to S3 in parallel.
redshift Acts as a fast data warehouse built on top of technology from massive parallel processing (MPP).
kinesis Streams data in real time with the ability to process thousands of data streams per second.
lambda Runs code in response to events, automatically managing compute resources.

 

commands

IPython Notebook(s) demonstrating various command lines for Linux, Git, etc.

Notebook Description
linux Unix-like and mostly POSIX-compliant computer operating system. Disk usage, splitting files, grep, sed, curl, viewing running processes, terminal syntax highlighting, and Vim.
anaconda Distribution of the Python programming language for large-scale data processing, predictive analytics, and scientific computing, that aims to simplify package management and deployment.
ipython notebook Web-based interactive computational environment where you can combine code execution, text, mathematics, plots and rich media into a single document.
git Distributed revision control system with an emphasis on speed, data integrity, and support for distributed, non-linear workflows.
ruby Used to interact with the AWS command line and for Jekyll, a blog framework that can be hosted on GitHub Pages.
jekyll Simple, blog-aware, static site generator for personal, project, or organization sites. Renders Markdown or Textile and Liquid templates, and produces a complete, static website ready to be served by Apache HTTP Server, Nginx or another web server.
pelican Python-based alternative to Jekyll.
django High-level Python Web framework that encourages rapid development and clean, pragmatic design. It can be useful to share reports/analyses and for blogging. Lighter-weight alternatives include Pyramid, Flask, Tornado, and Bottle.

misc

IPython Notebook(s) demonstrating miscellaneous functionality.

Notebook Description
regex Regular expression cheat sheet useful in data wrangling.
algorithmia Algorithmia is a marketplace for algorithms. This notebook showcases 4 different algorithms: Face Detection, Content Summarizer, Latent Dirichlet Allocation and Optical Character Recognition.

notebook-installation

anaconda

Anaconda is a free distribution of the Python programming language for large-scale data processing, predictive analytics, and scientific computing that aims to simplify package management and deployment.

Follow instructions to install Anaconda or the more lightweight miniconda.

dev-setup

For detailed instructions, scripts, and tools to set up your development environment for data analysis, check out the dev-setup repo.

running-notebooks

To view interactive content or to modify elements within the IPython notebooks, you must first clone or download the repository then run the notebook. More information on IPython Notebooks can be found here.

$ git clone https://github.com/donnemartin/data-science-ipython-notebooks.git
$ cd data-science-ipython-notebooks
$ jupyter notebook

Notebooks tested with Python 2.7.x.

credits

contributing

Contributions are welcome! For bug reports or requests please submit an issue.

contact-info

Feel free to contact me to discuss any issues, questions, or comments.

license

This repository contains a variety of content; some developed by Donne Martin, and some from third-parties. The third-party content is distributed under the license provided by those parties.

The content developed by Donne Martin is distributed under the following license:

I am providing code and resources in this repository to you under an open source license. Because this is my personal repository, the license you receive to my code and resources is from me and not my employer (Facebook).

Copyright 2015 Donne Martin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License