# Poisson Regression in R Language

Poisson Regression involves regression models in which the response variable is in the form of counts and not fractional numbers. For example, the count of number of births or number of wins in a football match series. Also the values of the response variables follow a Poisson distribution.

The general mathematical equation for Poisson regression is -

 log(y) = a + b1x1 + b2x2 + bnxn ........

Following is the description of the parameters used -

y is the response variable.
a and b are the numeric coefficients.
x is the predictor variables.

The function used to create the Poisson regression model is the glm( ) function.

Syntax

The basic syntax for glm( ) function in Poisson regression is -

 glm( formula, data, family)

Following is the description of the parameters used in above followings -
• formula is the symbol presenting the relationship between the variables.
• data is the data set giving the values of these variables.
• family is R object to specify the details of the model. It's value is 'Poisson' for Logistic Regression.
Example

We have the in-built data set "warpbreaks" which describes the effect of wool type (A or B) and tension (low, medium or high) on the number of wrap breaks per loom. Let's consider "breaks" as the response variable which is a count of number of breaks. The wool "type" and "tension" are taken  as predictor variables.

INPUT DATA

 input <-  warpbreaks  print (head(input) )

When we execute the above code, it producers the following result -

breaks            wool              tension

1              26                   A                     L

2              30                   A                     L

3              54                   A                     L

4              25                   A                     L

5              70                   A                     L

6              52                   A                     L

Create Regression Model

 output <- glm( formula = breaks ~ wool + tension,                                   data = warpbreaks,                                 family = poisson) print (summary (output) )

When we execute the above code, it produces the following result -

 Call : glm( formula = breaks ~ wool + tension, family = poisson, data = warpbreaks) Deviance Residuals :  Min           1Q          Median          3Q         Max -3.6871   -1.6503      -0.4269        1.1902    4.2616 Coefficients :                         Estimate Std. Error z value Pr (> | z |) (Intercept)   3.69196     0.04541    81.302   < 2e-16     *** woolB        -0.020599   0.05157    -3.994  6.49e-05     *** tensionM    -0.32132    0.06027    -5.332   9.73e-08     *** tensionH    -0.51849     0.06396    -8.107   5.21e-16     *** --- Signif.  codes:  0  '***'  0.001  '**'  0.01 '*'  0.05 '.'  0.1 '  '  1 (Dispersion parameter for poisson family taken to be 1 )        Null deviance: 297.37  on 53  degrees of freedom Residual deviance: 210.39  on 50  degrees of freedom AIC:  493.05 Number of Fisher Scoring iterations: 4

In the summary we look for the p-value in the last column to be less than 0.05 to consider an impact of the predictor variable on the response variable. As seen the wooltype B having tension type M and H have impact on the count of breaks.

# Grid View in Android Studio

In android GridView is a view group that display items in two dimensional scrolling grid (rows and columns), the grid items are not necessarily predetermined but they are automatically inserted to the layout using a ListAdapter. Users can then select any grid item by clicking on it. GridView is default scrollable so we don’t need to use ScrollView or anything else with GridView.
GridView is widely used in android applications. An example of GridView is your default Gallery, where you have number of images displayed using grid.
Adapter Is Used To Fill Data In Gridview: To fill the data in a GridView we simply use adapter and grid items are automatically inserted to a GridView using an Adapter which pulls the content from a source such as an arraylist, array or database.
GridView in Android Studio: Gridview is present inside Containers. From there you can drag and drop on virtual mobile screen to create it. Alternatively you can also XML code to create it.
Basic GridView code in XML:


Important Note: numColumns property has to be specified otherwise GridView behaves like a ListView with just singleChoice. In the above image numColumns property specified that there is 3 columns to show, if we set it to auto_fit then it automatically display as many column as possible to fill the available space of the screen. Even if the phone is in portrait mode or landscape mode it automatically fill the whole space.
Attributes of GridView:
Lets see different attributes of GridView which will be used while designing a custom grid view:
1.id: id is used to uniquely identify a GridView.
Below is the id attribute’s example code with explanation included in which we don’t specify the number of columns in a row that’s why the GridView behaves like a ListView.
Below is the id attribute example code for Gridview:



2.numColumns: numColumn define how many columns to show. It  may be a integer value, such as “5” or auto_fit.
auto_fit  is used to display as many columns as possible to fill the available space on the screen.
Important Note: If we don’t specify numColumn property in GridView it behaves like a ListView with singleChoice.
Below is the numColumns example code where we define 4 columns to show in the screen.



3. horizontalSpacing: horizontalSpacing property is used to define the default horizontal spacing between columns. This could be in pixel(px),density pixel(dp) or scale independent pixel(sp).
Below is the horizontalSpacing example code with explanation included where horizontal spacing between grid items is 50 dp.

 >
4.verticalSpacing: verticalSpacing property used to define the default vertical spacing between rows. This should be in px, dp or sp.
Below is the verticalSpacing example code with explanation included, where vertical spacing between grid items is 50dp.


5.columnWidth: columnWidth property specifies the fixed width of each column. This could be in px, dp or sp.
Below is the columnWidth example code. Here column width is 80dp and selected item’s background color is green which shows the actual width of a grid item.
Important Note: In the below code we also used listSelector property which define color for selected item. Also to see the output of columnWidth using listSelector we need to use Adapter which is our next topic. The below code is not sufficient to show you the output.


GridView Example Using Different Adapters In Android Studio:
An adapter is a bridge between UI component and data source that helps us to fill data in UI component. It holds the data and sends the data to adapter view, then view can takes the data from the adapter view and shows the data on different views like as list view, grid view, spinner etc.
GridView and ListView both are subclasses of AdapterView and it can be populated by binding  to an Adapter, which retrieves the data from an external source and creates a View that represents each data entry. In android commonly used adapters which fill data in GridVieware:

Now we explain these adapters in detail:

1. Avoid Array Adapter To Fill Data In GridView:
Whenever you have a list of single items which is backed by an array, you can use ArrayAdapter. For instance, list of phone contacts, countries or names.
By default, ArrayAdapter expects a Layout with a single TextView, If you want to use more complex views means more customization in grid items, please avoid ArrayAdapter and use custom adapters.

2. GridView Using Base Adapter In Android:
Base Adapter is a common base class of a general implementation of an Adapter that can be used in GridView. Whenever you need a customized grid view you create your own adapter and extend base adapter in that. Base Adapter can be extended to create a custom Adapter for displaying custom grid items. ArrayAdapter is also an implementation of BaseAdapter. You can read BaseAdapter tutorial here.
Example of GridView using Base Adapter in Android Studio: Below is the example of GridView in Android, in which we show the Android logo’s in the form of Grids. In this example firstly we create an int type array for logo images and then call the Adapter to set the data in the GridView. In this we create a CustomAdapter by extending BaseAdapter in it. At Last we implement setOnItemClickListener event on GridView and on click of any item we send that item to another Activity and show the logo image in full size.
Below you can download code, see final output and step by step explanation of the example.
Step 1: Create a new Android project in Android Studio and fill all the required details. In our case we have named GridViewExample and package com.example.gourav.GridViewExample
Step 2: Open activity_main.xml and paste the below code. In this we have created a Grid view insideLinear Layout and also set number of columns to 3.


Step 3: Create a new XML file and paste the below code. We have named activity_gridview.xml.
In this step we create a new XML file and add a ImageView in it. This file is used in CustomAdapter to set the logo images

Step 4:Now open drawable folder and save small size png images of different logo’s and name them like logo1,logo2 and etc.
Step 5: Now open MainActivity.java and paste the below code. If your package name is different, don’t copy it.
In this step firstly we get the reference of GridView and then create a int type array for Android logo’s. After that we call the CustomAdapter and pass the array in it. At Last we implement setOnItemClickListener event on GridView and on click of any item we send that item to another Activity to show the logo image in Full Size. I have added comments in code to help you to understand the code easily so make you read the comments.

 package com.example.gourav.GridViewExample; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; public class MainActivity extends AppCompatActivity {    GridView simpleGrid;    int logos[] = {R.drawable.logo1, R.drawable.logo2, R.drawable.logo3, R.drawable.logo4,            R.drawable.logo5, R.drawable.logo6, R.drawable.logo7, R.drawable.logo8, R.drawable.logo9,            R.drawable.logo10, R.drawable.logo11, R.drawable.logo12, R.drawable.logo13};    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        simpleGrid = (GridView) findViewById(R.id.simpleGridView); // init GridView        // Create an object of CustomAdapter and set Adapter to GirdView        CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), logos);        simpleGrid.setAdapter(customAdapter);        // implement setOnItemClickListener event on GridView        simpleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {            @Override            public void onItemClick(AdapterView parent, View view, int position, long id) {                // set an Intent to Another Activity                Intent intent = new Intent(MainActivity.this, SecondActivity.class);                intent.putExtra("image", logos[position]); // put image data in Intent                startActivity(intent); // start Intent            }        });    } }
Step 6: Create a new class CustomAdapter and paste the below code.
In this step we create a CustomAdapter class by extending BaseAdapter in it. In this step we set the logo image’s in the grid items. I have added comments in code to help you to understand the code easily so make you read the comments.

 package com.example.gourav.GridViewExample; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; public class CustomAdapter extends BaseAdapter {    Context context;    int logos[];    LayoutInflater inflter;    public CustomAdapter(Context applicationContext, int[] logos) {        this.context = applicationContext;        this.logos = logos;        inflter = (LayoutInflater.from(applicationContext));    }    @Override    public int getCount() {        return logos.length;    }    @Override    public Object getItem(int i) {        return null;    }    @Override    public long getItemId(int i) {        return 0;    }    @Override    public View getView(int i, View view, ViewGroup viewGroup) {        view = inflter.inflate(R.layout.activity_gridview, null); // inflate the layout        ImageView icon = (ImageView) view.findViewById(R.id.icon); // get the reference of ImageView        icon.setImageResource(logos[i]); // set logo images        return view;    } }
Step 7: Now Create a new XML file named activity_second and paste the below code in it.
In this step we create an XML file for our Second Activity to display the logo image in full size.



Step 8: Now Create a new Activity with name SecondActivity.class and add below code in it.
In this step we create a new Activity in which firstly we initiate the ImageView and then get the Image from our Previous Activity by using Intent object and set the same in the ImageView.

 package com.example.gourav.GridViewExample; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; public class SecondActivity extends AppCompatActivity {    ImageView selectedImage;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_second);        selectedImage = (ImageView) findViewById(R.id.selectedImage); // init a ImageView        Intent intent = getIntent(); // get Intent which we set from Previous Activity        selectedImage.setImageResource(intent.getIntExtra("image", 0)); // get image from Intent and set it in ImageView    } }
Output: Now run the App and you will see different Android images in GridView. Click on the any image and full size of it will open up.

3. GridView Example Using Custom ArrayAdapter In Android Studio:
ArrayAdapter is also an implementation of BaseAdapter so if we want more customization then we create a custom adapter and extend ArrayAdapter in that. Here we are creating GridView using custom array adapter.

Example of GridView using Custom Adapter : Example of Grid View using custom arrayadapter to show birds in the form of grids. Below is the code and final output:
Below you can download code, see final output and step by step explanation of the topic.
Step 1: Create a new project and name it GridViewExample.
Step 2: Now open app -> res -> layout -> activity_main.xml (or) main.xml and add following code :

Step 3: Create a new layout Activity in app -> res-> layout-> new activity and name it grid_view_items.xml and add following code:


Step 4: Now open app -> java -> package -> MainActivity.java

Step5 : Create a new Class src -> package -> MyAdapter.java and add the following code:

 import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; public class MyAdapter extends ArrayAdapter {    ArrayList birdList = new ArrayList<>();    public MyAdapter(Context context, int textViewResourceId, ArrayList objects) {        super(context, textViewResourceId, objects);        birdList = objects;    }    @Override    public int getCount() {        return super.getCount();    }    @Override    public View getView(int position, View convertView, ViewGroup parent) {        View v = convertView;        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);        v = inflater.inflate(R.layout.grid_view_items, null);        TextView textView = (TextView) v.findViewById(R.id.textView);        ImageView imageView = (ImageView) v.findViewById(R.id.imageView);        textView.setText(birdList.get(position).getbirdName());        imageView.setImageResource(birdList.get(position).getbirdImage());        return v;    } }
Step 6: Create a new Class src -> package -> Item.java and add the below code:

 public class Item {    String birdListName;    int birdListImage;    public Item(String birdName,int birdImage)    {        this.birdListImage=birdImage;        this.birdListName=birdName;    }    public String getbirdName()    {        return birdListName;    }    public int getbirdImage()    {        return birdListImage;    } }
Output:
Now run the App and you will see different bird images in GridView.

## Categories

AI (27) Android (24) AngularJS (1) aws (17) Azure (7) BI (10) book (4) Books (114) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (89) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (742) Questions (2) R (70) React (6) Scripting (1) security (3) Software (17) SQL (40) UX Research (1)