Cognizant Data Science Interview Questions & Answers
Curated interview practice questions with answers. These are practice scenarios, not a verified list of past interview questions.
Solved for CognizantStart practicing
3 QUESTIONS FREESign up or log in to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
02
How does K-means clustering work and how do you choose k?
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
04
What is the difference between regression and classification?
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
06
What is the difference between parametric and non-parametric tests?
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
15
How does linear regression work and what are its assumptions?
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
17
How would you fine-tune a pretrained language model for classification?
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
18
What are precision and recall trade-offs in practice?
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
33
What is the difference between generative and discriminative models?
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
34
Which activation functions do you know and when to use them?
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
36
What is the difference between mean, median and mode?
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
39
What is multicollinearity and how do you handle it?
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
40
What is the difference between a function and a method?
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
52
Pandas: find the top 3 products by revenue in each region.
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
54
Your dataset is highly imbalanced (2% positives). How do you handle it?
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
56
What is the difference between a set and a dictionary?
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
58
How do you use groupby with multiple aggregations?
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
61
What is gradient descent and what does the learning rate do?
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
66
Why do we use activation functions? Why is ReLU popular?
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.