Wednesday, August 14, 2019

Assumptions of Linear Regression & Hypothesis Testing

In the previous blog we learnt how to use Linear Regression to predict response variables with only one predictor / dependent variable. As there was only one response and one dependent variable, it was termed as Linear Regression.
For the simplicity of implementing mathematical and computational techniques on the dataset for prediction, we apply certain generic  assumptions on the dataset for this regression :-

  1. Linearity -  Independent and dependent variables should / must have relationship between each other. Relationship between variables can be understood or tested by plotting them on the graphs.

  1. Homoscedasticity - The variance of all random variables in a dataset is finite. Scatter plot can show whether data are homoscedastic or not.

  1. Lack of Multicollinearity - Multicollinearity occurs when more than two independent variables are highly correlated with each other. This doesn't occur here as there's only one independent variable in the dataset.

  1. Multivariate Normality -  All correlated random variables clusters around a mean value. This assumption can be tested by plotting the histogram which usually shows normality ( left / right aligned ) of the data.

  1. Independence of Errors  - Linear regression analysis requires that the residuals of the data is not independent from each other. Autocorrelation occurs when the residuals are not independent from each other. This can be tested using Null Hypothesis

Hypothesis Testing :

Hypothesis is the statement or an assumption about relationships between variables.
Criteria for constructing Hypothesis is that,
  1. It should be precise and not contradictory
  2. It should be testable whether it is right or wrong.
  3. Should specify the variables between which the relationship is established.

Types of Hypothesis :

  1. Null Hypothesis ( H0 )  - Null Hypothesis claims that there's no different in the population of data.
  2. Alternative Hypothesis ( H0 or H1 ) - Alternate Hypothesis claims H0 is false.

Hypothesis testing is also called Significance testing.

The Major purpose of hypothesis testing is to choose between two competing hypothesis about the value of a population parameter. For Ex:- If

One hypothesis says the salaries of men and women at every level is equal, while the alternative might claim that it is false.
Null Hypothesis usually referred with the symbol H0 and the other hypothesis which is assumed to be true when the null hypothesis is proved false, which is referred as alternative hypothesis.

Generally, for the sake of convenience we take the Null Hypothesis on the equal side for the sample of population, so that, when it is proved false, the alternative will be either less than or more than a certain value associated with the null hypothesis.

Ideally, true value of the population parameter should be included in the set specified by H0 or in the set specified by H1.

There's a very famous illustrative example of "Body weight"  where the age group of 20 - 29 years old men in US had a mean body weight of 170 pounds. Standard deviation   σ = 40 pounds.
So, here we test the
  1. Null hypothesis H0 = µ = 170 pounds
  2. Alternative hypothesis = H1 =  µ > 170 pounds or µ < 170 pounds.

Let's say we take multiple random samples of data to validate the Null hypothesis.
Random samples of n = 64.
Based on the Sampling Distribution of a Mean ( SDM ) :  Xbar = N( µ, SE )   where SE =  σ / √n

Applying this formula to calculate the Zstat :-   Zstat =  Xbar - µ0 / SE  ( Where µ0 = population mean )

Test Statistic Zstat = Xbar - µ0  / ( σ / √n )

Now, we will take a few samples from the population where Sample mean Xbar is  ( first sample mean = 172, second sample mean = 164 )
Substituting the values of  µ0 = 170,  σ = 40, and SE = 5  in various samples
We will get the Zstat scores as follows
  1. Test Statistic Zstat1  =  ( 172 - 170 ) / 5  = 0.4  
  2. Test Statistic Zstat2  = ( 183 - 170 ) / 5   = 2.6
  3. Test Statistic Zstat3  = ( 164 - 170 ) / 5 = -1.2

Now Calculating the P-Value - AUC ( Area Under Curve ) of the above found test statistic.

P-Value :- is the probability of obtaining a sample that is closer than the observed data, assuming that H0 ( Null hypothesis ) is true.

P-Value is a calculation that we make during the hypothesis testing to determine if we reject the null hypothesis or fail to reject it.

How to find P-Value :   P-Value is calculated by first determining the Zstat score. Then, we find the probability in a normal distribution table and then interpret the results by comparing the p-value to the level of significance.
Normal distribution chart to find P-Value is available on the back of every statistical text book and also easily available on the internet.
Normal Distribution chart can be found here :

Calculating the p-Value :-  Probability(Zstat)

P-Value of Zstat1 =  0.6554 
P-Value of Zstat2 = 0.9953  
P-Value of Zstat3  =  0.1150

These P-Values corresponds to the AUC ( Area Under Curve ) in the tail of  the standard Normal Distribution beyond the Zstat.

As mentioned above,  P-Value is the probability of the observed test statistic when H0 Null Hypothesis is true.
Hence, smaller and smaller the P-Values provide stronger evidence against H0

In this scenario, if we have 5% probability of erroneously rejecting the H0. in other words, setting the threshold Ɛ = 5% = 0.05 to erroneously rejecting the H0.
  1. Reject H0 if P <= Ɛ
  2. Retain H0 if P > Ɛ

Example:-  If  Ɛ = 0.05 and P = 0.655  =>   Retain H0


SUMMARIZING THE EVENTS FOR HYPOTHESIS TESTING :-

  1. State H0 and H1
  2. Specify the level of significance ( Ɛ )
  3. Decide the appropriate sampling distribution
  4. Calculate the Zstat ( test statistic)  using the formula mentioned above.
  5. Lookup for the Probability P-Value of the Zstat ( test statistic)
  6. If the P-Value is smaller than the Ɛ value - Reject the Hypothesis else Retain the Hypothesis

Thursday, August 8, 2019

Simple Linear Regression with R & Python


Simple Linear Regression is a process of regression in finding relationship of dependent and independent continuous quantitative variables.  It is called Simple because there's only one independent / explanatory or predictor variable that is used to predict the relationship dependency

The Formula for Simple Linear Regression is  : Y = β0 + β1* X + Ɛ


Here Y is the dependent Variable - Ex : How the Salary changes with the No.Of.YearsOfExperience, where Y is the Salary

and X is the Independent Variable ( Yrs.of.experience ). X is a variable that is causing the dependent variable to change based on unit of rate of change occurs in X.
There is still a possibility that there's no direct correlation between the two, but, still have a sort of implied association between dependent and independent variable.

 β1 <- is the coefficient of X, it shows how a unit change in X shows the degree change in Y, which implies that there's a proportion of change that occurs between X & Y and not a one to one change in units.

β0  <- is a constant or Intercept of the slope, which indicates a value when β1 is 0. i.e., when β1 is 0, X = 0 and hence, Y = β0 which is constant OR an intercept of the slope when X = 0.

Let us look at this in the graph for plotting Salary vs Yrs.of.experience.

For any prediction using Classic Machine Learning / Neural Network techniques, there are 5 major steps to be followed [ Fundamentals of Machine Learning ]
  1. Finding the data based on problem statement.
    1. Finding appropriate data for correct analysis
  2. Exploratory data analysis
    1. Understand the data spread and outliers
    2. Visualize the data
    3. Preparing your data
    4. Use Feature engineering on the data as necessary for applying suitable algorithms to train the model.
  3. Fit / Train the model - using appropriate algorithm
    1. Use of appropriate algorithm to train/Fit the model
    2. Developing a model that does better than a baseline
    3. Regularizing the model and turning Hyperparameters.
  4. Apply prediction using the trained model.
    1. Use validation & test data for testing the model
  5. Testing & Data Visualization
    1. Validate results / accuracy using test data sets
    2. Use data visualization techniques to visualize the results.

We will follow these steps, as applicable based on sanity of the data,

We will start with Predicting Salary from the given data with no. of years of experience.

You can find the data file here

You can also find the entire code in this Github repo

Predicting Salary with Simple Linear Regression using R :-


#Import the dataset
dataset = read.csv("Salary.csv")

#install.packages('caTools')
library(caTools)
set.seed(123)

#Splitting the Dataset into Training and Testing dataset.
fragment = sample.split(dataset$Salary, SplitRatio = 2/3, group = NULL)
trainingset = subset(dataset, fragment == TRUE)
testset = subset(dataset, fragment == FALSE)

#Fitting simple Linear model to training set
LinearRegressor = lm(formula = Salary ~ YearsOfExperience,
                     data = trainingset )

summary(LinearRegressor)

<<<<Output of Summary >>>>
#The above command will show summary of the fitted model.
Residuals:
    Min                1Q              Median              3Q               Max
-9279.5          -4339.5         -648.5             3620.7         9748.9
Coefficients:        Estimate Std. Error t value Pr(>|t|)   
(Intercept)               31792.0     1935.7   16.42   <2e-16 ***    <= Intercept is the slope β0 i.e.,, when X = 0, Y =  β0
YearsOfExperience   7739.4      161.9   47.79    <2e-16 ***    <=  *s denotes the significance of the var on Response var
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 5663 on 31 degrees of freedom
Multiple R-squared:  0.9866,        Adjusted R-squared:  0.9862
F-statistic:  2284 on 1 and 31 DF,  p-value: < 2.2e-16

#Predicting the Test Set Results
Predictor = predict(LinearRegressor, newdata = testset)

# Plotting the graph on test set results using ggplot2
#install.packages('ggplot2')
library(ggplot2)

ggplot() +
  geom_point(aes(x = testset$YearsOfExperience, y = testset$Salary),
             colour = 'blue') +
  geom_line(aes(x = testset$YearsOfExperience, y= Predictor),
            colour = 'red') +
  ggtitle('Salary vs Experience') +
  xlab('YearsOfExperience') +
  ylab('Salary')



With Graph plotted, we can see that there's a difference between the Actual Salary and the Predicted Salary.
Based on the Multiple R-squared:  0.9866,        Adjusted R-squared:  0.9862 values, we can evaluate the accuracy of the Prediction.


Predicting Salary with Simple Linear Regression using Python :-


For executing the below code in python, you can use any of the interfaces like ( Jupyter notebook, Pycharm , Spyder  or a plain notepad++ )

I have used Notepad++ and executed through iPython console. Same steps have been applied in both the platforms to predict the response variable.

#Importing libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#Importing the data
dataset = pd.read_csv('Salary.csv')

# Validate the dataset
dataset.describe()

# Split into Dependent and Independent variables
X = dataset.iloc[:,:-1].values
Y = dataset.iloc[:, 1].values

#X = dataset.YearsOfExperience
#Y = dataset.Salary

# No Manipulation or Imputation of data is needed as this is a Simple and clean dataset.
# Splitting the dataset to Train and Test data.
from sklearn.cross_validation import train_test_split
Xtrain, Xtest, Ytrain, Ytest = train_test_split(X,Y, test_size = 0.3, random_state = 1)

#Fitting the Simple Linear Regression Model
from sklearn.linear_model import LinearRegression
LinearRegressor = LinearRegression()
LinearRegressor.fit(Xtrain, Ytrain)

# Predicting the Test Set Results
YPredictor = LinearRegressor.predict(Xtest)

# Evaluating the Intercept
LinearRegressor.intercept_

#Plotting the Graph for Predicted Test Set Results
plt.scatter(Xtest, Ytest, color = 'blue')
plt.plot(Xtest, YPredictor, color = 'red')
plt.title('Experience vs Salary')
plt.xlabel('Number of Years of Experience')
plt.ylabel('Salary')
plt.show()

#Predicting for any random value
YPred = LinearRegressor.predict([[16.5]])
print(np.float32(YPred))

#Calculating the R Squared value for accuracy
from sklearn.metrics import r2_score
print("r2_score",np.float32(r2_score(Ytest,YPredictor)*100))



In the next blog, we will talk about the Assumptions of Linear Regression and Hypothesis testing.

Regression Analysis with Simple Linear Regression



Regression analysis is defined as applying a set of statistical processes to estimate the relationship between variables. Many techniques are involved in modeling and analyzing these variables.
Regression analysis helps us understand how the values of dependent variables changes when there's a variation in 
any of the independent variables while dealing with multiple independent variables.

We can even understand the variation trend of dependent variables by slightly varying any one of the independent variables and keeping others fixed.

Let’s start with Simple Linear Regression and proceed further with multiple linear regression.

Simple Linear Regression :

As mentioned before, Simple Linear Regression is a process of regression in finding relationship of dependent and independent continuous quantitative variables.  It is called Simple because there's only one independent / explanatory or predictor variable that is used to predict the relationship dependency

In "Multiple" Linear regression, two or more independent variables are used to predict the dependency of a Response variable.

Simple Linear Regression is represented by the formula Y = β0 + β1* X + Ɛ

Here,  β1 is the independent ( explanatory ) variable and Y is the dependent variable. That means, the slight variation of independent variable ( β1 ) will result in variation of predictor (  β0 ) variable.

Identifying / estimating the Correlation & Co-variance between these two variables by regression is defined as the relationship between these two variables.

Covariance shows the direction of the relationship between these variables

Correlation shows the strength of the relationship between these variables.

Covariance, as name suggests, shows how the dependent variable varies when the independent variable is varied.

Let us consider an equation y = mx + c

y = mx + c is an equation of a straight line and the direction of variation on y can be measured by the variation that happens on x.

Lets consider a sample data set of temperature in Fahrenheit v/s heartbeat. ( for the sake of simplicity, I have considered only male data to ignore gender column from the dataset )


degrees
beats per minute
98.4
84
98.4
82
98
78
97.9
72
98.5
68
98
67
97.4
78
98.8
78
99.5
75
97.1
75
98
71
98.9
80
99
75
98.6
77
96.7
71


Now, here Y = beats per minute & X = temperature.

To understand the covariance, let's take the mean of X & Y

Sample mean of Y Ymean = 98.2 degrees.  With the formula provided here
Sample mean of X Xmean = 75.4 degrees.
Understanding the deviation of each observation from the mean Yi & Xi and taking the product.


Product = ( Yi - Ymean ) * ( Xi - Xmean )

Quadrant
Yi - Ymean
Xi - Xmean
( Yi - Ymean ) ( Xi - Xmean )
Relationship
1
+
+
+
+
2
+
-
-
-
3
-
+
-
-
4
-
-
+
+

Plotting the graph with X & Y coordinates and understanding the linear relationship between X & Y as follows :

If the plotted points are in 1st and 3rd Quadrant  -> relationship is positive, i.e.,  if X increases, Y also increases
If the plotted points are in 2nd and 4th Quadrant -> relationship is negative, i.e., if X increases, Y decreases.

Hence, covariance of the variables can be defined as :-


Understanding the covariance between Y & X will provide the direction of how the variables are related to each other.

Substituting the values of the above table in Covariance formula :

COV(Y, X) =  ((98.4 - 98.21)(84-75.4)+(98.4-98.21)(82-75.4)+98 - 98.21)(78-75.4)+……)/ ( 15 - 1))
COV(Y, X) =  13.42000 / 14
COV(Y, X) =  0.9585 * 100 = 95.85%

If Cov(Y,X)  > 0  then we can understand that Y & X are positively correlated  if Cov(Y,X)  < 0 then Y & X have negative relationship.

With this, we can understand that the direction for Y & X is positive

Understanding the Covariance, we can derive the Correlation of the variables :-

Correlation can be defined as :


Where Sy & Sx are the standard deviations of Y & X respectively.

Substituting the Covariance and Standard Deviation :-

COR(Y, X) =  0.9585 / ( 0.75 * 12.10)
COR(Y, X) =  0.1059 * 100 = 10.59 %

This indicates the strength of variables - for every unit increase in X there will be a 10.59% increase in Y.

Standardizing the Data

Standardizing the data means, If the data of Y & X are ranging between thousands of units and they can't be compared or plotted in a graph, these numbers will be standardized based on certain rules.
  1. Subtract the observations from mean value.
  2. Divide each observation by standard deviation  ( check here for standard deviation )

Standardizing Y & X, we will arrive at the above mentioned formula for Correlation.

Correlation can be defined as Covariance between the standardized variables or the ratio of the Covariance to the standard deviation of the two variables.

Calculating the Correlation, result lies between -1 & +1

-1 <= COR ( Y,X ) <=  +1

Hence, these properties make the correlation of Y & X ( Response & Independent variables ) a useful quantity for measuring the direction and strength of the relationship between variables.

More the Cor(Y,X) towards +1, relationship between Y & X is said to be stronger and vice versa.


Monday, January 21, 2019

Introduction to Basic Statistics



I will be starting a series of Machine Learning Algorithms and gradually take over to advance level and encourage everyone to learn Machine Learning and Artificial Intelligence Algorithms and apply them in the real-world problems.

To start with, I would like to start from the real basics of Statistics like : Mean, Median, Standard Deviation, Quartiles & Percentiles. This will help to have good basics around simple statistics.
Of course, we all would have learnt in our High School classes. However, this will brush up our learning to go through and understand what they mean and how they are derived.

Mean  :-  Mean value or Mean is the average value of any given data set. This is simple, but, why do we need Mean ? what is the use of           mean ?  Mean is termed as Representation of any given data set.

For Ex :-  the weights of students in a class. So, now, if this data set has to be summarized, we usually take the average that data-set and represent as an average weight of that class is =  X Kgs / pounds.

So, Mean is generally used as the representation of any given data set.

Statisticians often refer to the mean and median as measures of Central tendency

How do we calculate Mean ?

Mean = ( Sum of observations ) / Number of observations => Average of the data set OR Mean of data set


Formula for calculating mean is :-  Mean is often termed as mu ( μ )


 ranging from 1 to  where being the number of observations of a given data set. 

Median :- Median is similar to mean, with the data arranged in ascending order and then choose the mid-point of the No. Of Observations.

If, the ( Count of Observations )  is an odd number, it is fairly easy to find the median = middle value.

Sample Median =   X( ( n + 1) /2 ),  where n is odd,

If the ( Count of Observations )  is even, then, median =  sum of two middle values / 2 

Sample Median =  1/2 X (n/2) , 1/2 x ( (n+1)/2), where n is even

The Sample Median is mostly preferred over Sample Mean, especially, if the data is asymmetric, i.e., if the data is not balanced and if there are too many outliers that is not balancing the data to measure the central tendency.

Couple of important differences between Mean and Median are :-

Mean
Median
Average of the data set and also called / known as Center of distribution
The mid-number of the set of numbers arranged / sorted in ascending order
Minimizes the sum of squared deviations i.e., Sum of the squares of the deviations ( Squares of each observation when subtracted from Mean ) is less when compared to sum of squares of deviations from Median
Minimizes the sum of absolute deviations I.e.,  Absolute sum of deviations ( sum of the every observation after subtracting from Median) is less when compared to absolute deviations from Mean.

Note:- #2  holds good for the data which has outliers and where there's a significant difference between Mean and Median, else, if mean and median are almost same, then the sum of squared deviations of mean and sum of absolute deviations of Median will be close to each other.



Standard Deviation :- is the deviation of every observation from the mean value. Standard deviation is the square root of sum of squares of the difference between mean and every observation of the data set, given by the formula.


i ranging from 1 to n and Yi is the ith  observation &  is the mean of a data set.

Inter Quartiles Range IQR :-  Interquartile Range is a measure of statistical spread of the difference between 75th and 25th percentiles, or between upper and lower quartiles,  IQR is calculated as

IQR = Q₃ − Q₁.

IQR is also called the mid spread or the middle 50% of the data or the H spread.
How to compute the IQR :-
  1. Sort the data in ascending order
  2. Find the Median ( Q2 )
  3. Find Medians of both upper half ( Q3 ) ( 75th percentile )  and Lower half ( Q1 ) ( 25th Percentile )
  4. IQR is the difference between Q3 & Q1. 


Below diagram shows different Quartiles and to find IQR

Q2 = Median
Q1 = Lower half median
Q3 = Upper half median


Outlier :  An outlier is an observation point that is distant from other observations. An outlier may be due to variability in the measurement or it may indicate experimental error.

       Outlier can be identified as Values >  Q3 +1.5 * (IQR) &  <  Q1 - 1.5 * (IQR)  of a given data set.


Cheers,
:-Deepak



Tuesday, January 31, 2017

TO MONITOR THE SQL DB Connection & Statistics ( Azure & On-Premises)

Usually when you want to understand the SQL Usage, it is also better to look at the number of connections SQL Server has made to get an understanding of what kind connection is being made and from how long users are connected to the SQL DB/Instance.

We can use the below simple Queries  to identify the number of connections the SQL Instance is running at that moment.


USE MASTER
GO

SELECT
      E.CONNECTION_ID,
      S.SESSION_ID,
      S.LOGIN_NAME,
      S.LAST_REQUEST_END_TIME,
      S.CPU_TIME
FROM
      SYS.DM_EXEC_SESSIONS S
      INNER JOIN SYS.DM_EXEC_CONNECTIONS E
      ON S.SESSION_ID = E.SESSION_ID
GO


USE THE BELOW QUERY TO RUN IT ON AZURE SQL TO OBTAIN THE CONNECTION STATISTICS


We can use the below mentioned query to obtain connection Statistics on SQL Azure.


SELECT * FROM SYS.DATABASE_CONNECTION_STATS
WHERE DATABASE_NAME = '<DATABASENAME>' AND START_TIME > '<TIMESTAMP>' --Provide Time in this format '2014-06-12 00:00:00.0000000'
ORDER BY START_TIME DESC

TO FIND SQL CPU & ACTIVE SESSIONS FOR LAST 24 HOURS - SQL Azure.

Sometimes, as DBAs at times you might want to know what are the Active Sessions and CPU Utilization / Usage for the last 24 hours. It is very useful to keep a tab on the Usage of SQL CPU/ Active Sessions. Especially, in the Cloud Era, we should know the DTU ( Database Throughput Unit ) of the SQL Server that you are choosing to spin up in Cloud environment. Also, in the Portal, most of the service providers will show a rolling dashboard for a max of 3 months.

In case, if you want to understand the trend of what was the usage of SQL CPU and Active Sessions for a period of One Year in Azure that can help you decide on what pricing tier you should choose. 

Here's what we can do :- 

Use the below mentioned query and schedule a job from any of your VMs ( because SQL Agent is not available in SQL PAAS Or Create a Powershell cmd / Task Scheduler jobs to run the query ) and populate them in a History table on a daily basis. 
Keep a tab on the Active Sessions and CPU Utilization of the SQL Instance / Server over a period of time to understand the usage/utilization to take better decisions on choosing appropriate SQL DTU / SKU that suits your needs which in turn can be cost effective as well.

USE MASTER

SELECT TOP 288 START_TIME, END_TIME, ACTIVE_SESSION_COUNT, ACTIVE_WORKER_COUNT, AVG_CPU_PERCENT,
AVG_PHYSICAL_DATA_READ_PERCENT,AVG_LOG_WRITE_PERCENT
FROM SYS.RESOURCE_STATS 
WHERE DATABASE_NAME = '<DATABASENAME>' 
ORDER BY START_TIME DESC

hope this helps :)

How To Identify Fragmentation levels of Indexes and Defragment them Regularly ?

We often come across Developers / DBAs talking about the Job runs taking really long or the queries are taking very long to provide output. The First thing everyone thinks about is to check if there are any blocks / look at the fragmentation level / How long does the query take to pull the data.

Although it is simple to run some queries and fetch the results, but, it needs some manual efforts on understanding the fragmentation levels and which indexes needs to be Reorganized / Rebuilt.

Hence, I have come up with a simple stored procedure that identifies fragmentation level and then Reorganizes or Rebuilds them based on a certain percentage.

Here is the SP Query that we can use to create as a Stored Procedure and 
Create a SQL Agent Job to execute this SP based on whatever frequency suitable for your database system.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spDefragmentIndexes]
@readonly BIT = 0,
@RunDefragmentIndexes bit = 1,
@maxfrag DECIMAL=30
AS
BEGIN
-- Declare variables
SET NOCOUNT ON
DECLARE @tablename VARCHAR (128)
DECLARE @execstr VARCHAR (255)
DECLARE @objectid INT
DECLARE @objectowner VARCHAR(255)
DECLARE @indexid INT
DECLARE @frag DECIMAL
DECLARE @indexname CHAR(255)

IF ISNULL(@RunDefragmentIndexes,0) = 1
BEGIN
-- CREATE THE TEMPORARY TABLE TO HOLD FRAGMENTATION INFORMATION
CREATE TABLE #FragmentedIndexes (
 DBName  CHAR (255)
,TableName  CHAR (255)
,IndexName  CHAR (255)
,ObjectID INT
,index_type_desc  CHAR (255)
,IndexSpaceUsedBytes DECIMAL
,avg_fragmentation_in_percent DECIMAL
,fragment_count INT
,avg_fragment_size_in_pages DECIMAL
,page_count INT
)

INSERT INTO #FragmentedIndexes (DBName,TableName,IndexName,ObjectID,index_type_desc,IndexSpaceUsedBytes,avg_fragmentation_in_percent,fragment_count,avg_fragment_size_in_pages,page_count)
SELECT
 DB_NAME() AS DBName
,'[' + s.Name + '].[' + OBJECT_NAME(ps.object_id) + ']' AS TableName
,i.name AS IndexName
,i.object_ID As ObjectID
,ips.index_type_desc
,ps.reserved_page_count*8.0*1024 AS IndexSpaceUsedBytes
,ips.avg_fragmentation_in_percent
,ips.fragment_count
,ips.avg_fragment_size_in_pages
,ips.page_count
FROM sys.dm_db_partition_stats ps
INNER JOIN sys.indexes i
ON  ps.object_id = i.object_id
AND ps.index_id = i.index_id
LEFT JOIN sys.Tables t on t.object_id = ps.object_id
LEFT JOIN sys.schemas s on s.schema_id = t.schema_id
CROSS APPLY sys.dm_db_index_physical_stats(DB_ID(), ps.object_id, ps.index_id, null, 'LIMITED') ips
ORDER BY ips.avg_fragmentation_in_percent desc, ps.object_id, ps.index_id


IF @readonly = 1
BEGIN

-- WRITE TO OUTPUT START TIME FOR INFORMATION PURPOSES
--SELECT 'CURRENTLY FRAGMENTED INDEXES'

SELECT TableName, ObjectOwner = user_name(so.uid), ObjectId, IndexName, avg_fragmentation_in_percent
FROM #FragmentedIndexes f
JOIN sysobjects so ON f.ObjectId=so.id
WHERE avg_fragmentation_in_percent >= @maxfrag
 AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') > 0
Order by avg_fragmentation_in_percent desc
END

-- BEGIN STAGE 2: (DEFRAG) DECLARE CURSOR FOR LIST OF INDEXES TO BE DEFRAGGED

DECLARE indexes CURSOR FOR
SELECT TableName, ObjectOwner = user_name(so.uid), ObjectId, IndexName, avg_fragmentation_in_percent
FROM #FragmentedIndexes f
JOIN sysobjects so ON f.ObjectId=so.id
WHERE avg_fragmentation_in_percent >= @maxfrag
 AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') > 0 

-- OPEN THE CURSOR

OPEN INDEXES

-- LOOP THROUGH THE INDEXES

FETCH NEXT
FROM INDEXES
INTO @tablename, @objectowner, @objectid, @indexname, @frag

IF @readonly = 1
BEGIN
-- WRITE TO OUTPUT START TIME FOR INFORMATION PURPOSES

SELECT 'Started defragmenting indexes at ' + CONVERT(VARCHAR,GETDATE())
END

WHILE @@FETCH_STATUS = 0
BEGIN
SET QUOTED_IDENTIFIER ON

--SELECT 'Now executing on ' + RTRIM(@indexname) + ' from table ' + RTRIM(@tablename) + ' with fragmentation of ' + CAST(@frag AS Varchar(10))
--SELECT(@execstr)

BEGIN TRY
IF (@frag < 30)
BEGIN
SELECT @execstr = 'ALTER INDEX [' + RTRIM(@indexname) + '] ON ' + RTRIM(@tablename) + ' REORGANIZE '
END
ELSE 
BEGIN
SELECT @execstr = 'ALTER INDEX [' + RTRIM(@indexname) + '] ON ' + RTRIM(@tablename) + ' REBUILD WITH (ONLINE = ON)'
END

IF (@readonly = 0)
BEGIN
 EXEC (@execstr)
END
END TRY
BEGIN CATCH
SELECT @execstr = 'ALTER INDEX [' + RTRIM(@indexname) + '] ON ' + RTRIM(@tablename) + ' REBUILD WITH (ONLINE = OFF)'
IF (@readonly = 0)
BEGIN
 EXEC (@execstr)
END
END CATCH
--UPDATE STATS AFTER INDEX REBUILD / REORGANIZE

SELECT @execstr = 'UPDATE STATISTICS ' +  RTRIM(@tablename) 
EXEC (@execstr)

SET QUOTED_IDENTIFIER OFF

FETCH NEXT
FROM INDEXES
INTO @tablename, @objectowner, @objectid, @indexname, @frag
END

-- CLOSE AND DEALLOCATE THE CURSOR

CLOSE INDEXES
DEALLOCATE INDEXES

IF @readonly = 1
BEGIN
-- Report on finish time for information purposes
SELECT 'Finished defragmenting indexes at ' + CONVERT(VARCHAR,GETDATE())
END
select *from #FragmentedIndexes
drop table #FragmentedIndexes
END
END

Multiple Linear Regression

Multiple Linear Regression is a process that uses multiple explanatory variables to predict the outcome of a response variable . The pu...