Friday, August 25, 2017

Unlocking Kafka Exactly-one Semantic

How to implement “Exactly-one Semantics” at Kafka side. Before that you, you have to check Kafka version:

If its Kafka 0.11 release then you can try enabling Exactly-once semantics feature. Prior to 0.11 Kafka support at least one delivery but that can cause duplicate results

Exactly-once one semantics has been implemented using concept. Idempotence and Transaction Management features
How to enable Exactly-once Semantics

In Producer config, please add/modify below property
enable.idempotence = True
acks=all
retries=Integer.MAX_VALUE
max.inflight.requests.per.connection=1
transactional.id =  < some unique id>

In Consumer config, please add/modify below property
isolation.level =  <read_committed or read_uncommitted>



References:

https://cwiki.apache.org/confluence/display/KAFKA/KIP-98+-+Exactly+Once+Delivery+and+Transactional+Messaging

https://cwiki.apache.org/confluence/display/KAFKA/KIP-129%3A+Streams+Exactly-Once+Semantics


https://www.confluent.io/blog/exactly-once-semantics-are-possible-heres-how-apache-kafka-does-it/

Tuesday, February 7, 2017

Hadoop multinode cluster setup on ubantu using apache ambari

1. Pre-requsite

# setup password less ssh


# turn off iptables
https://help.ubuntu.com/community/IptablesHowTo#Configuration%20on%20startup

# disable silenix

# disable ipv6


2. Prepare for setup

cd /etc/apt/sources.list.d

 wget http://public-repo-1.hortonworks.com/ambari/ubuntu14/2.x/updates/2.2.2.0/ambari.list 

  apt-key adv --recv-keys --keyserver keyserver.ubuntu.com B9733A7A07513CAD
  apt-get update
  apt-get install ambari-server


ambari-server setup

go with default

ambari-server start


Access ambari server using ip or localhost:8080

#How to completly uninstall ambari/hadoop

apt-get remove ambari-server
apt-get remove ambari-agent
apt-get purge postgresql

rm -rf /usr/lib/ambari-*
rm -rf /etc/ambari/*
rm -rf /var/log/ambar/*

http://www.yourtechchick.com/hadoop/how-to-completely-remove-and-uninstall-hdp-components-hadoop-uninstall-on-linux-system/

https://community.hortonworks.com/questions/1110/how-to-completely-remove-uninstall-ambari-and-hdp.html

 Ip points

# all serves should have all servers host entry in /etc/host
 # remove localhost details

# Start with basic setup(HDFS and Yarn+MapReduce) first






 

Monday, October 17, 2016

Spark Setup and installation on window

Spark Setup and installation on window

1. Download r
https://cran.r-project.org/mirrors.html
2. Download Scala
http://www.scala-lang.org/download/2.10.6.html
3. Jdl 1.7 +
4. Download python

5. After saving the file I have downloaded the hadoop binary file winutils.exe, even though Spark runs independently of Hadoop, there is a bug which searches for winutils.exe which is needed for hadoop, and throws up an error.

I have download the file from the below mentioned link

http://public-repo-1.hortonworks.com/hdp-win-alpha/winutils.exe

I have created a folder named winutils in c:\ and created bin directory and placed the winutils.exe file in it. The file location is as follows.

C:\winutils\bin\winutils.exe

6. Setup envionrment variable
Pressing WIN + R button which open’s up the run and enter sysdm.cpl
I then clicked on advanced tab and then on environment variables. Clicked new for the user variables and added the following

variable name as HADOOP_HOME  and it's value as C:\winutils
variable name as SPARK_HOME and it's value as C:\spark

7. Install Jupyter
https://jupyter.readthedocs.io/en/latest/install.html

8. run jupyter notebook

*************************

Continue with reading
http://spark.apache.org/docs/latest/programming-guide.html#overview

************************


Troubleshooting stesps

Wrong => trainErr = labelsAndPreds.filter(lambda (v, p): v != p).count() / float(parsedData.count())
right Pytyon 3.0=> testErr = labelsAndPredictions.filter(lambda v: v[0] != v[1]).count() / float(testData.count())

model = DecisionTree.trainClassifier(trainingData, numClasses=2, categoricalFeaturesInfo={},impurity='gini', maxDepth=5, maxBins=32)



Error
[1] "The data can be downloaded from: http://s3-us-west-2.amazonaws.com/sparkr-data/flights.csv "

  java.lang.ClassNotFoundException: Failed to find data source: com.databricks.spark.csv. Please find packages at http://spark-packages.org

Thursday, September 1, 2016

Hive LLAP (Live Long and Process)

hive> set hive.llap.execution.mode=none;

to change into llap mode use the following command

hive> set hive.llap.execution.mode=all;

LLAP is an optional daemon process running on multiple nodes, that provides the following

- Caching and data reuse across queries with compressed columnar data in-memory

- Multi threaded execution including reads with predicate pushdown and hash join

- High throughput IO using Asynch IO Elevator with dedicated thread and core per disk

- Granular column level security across applications

Tuesday, May 17, 2016

Shipping BigData Science Tools in Docker Container

Shipping BigData Science Tools in Docker Container




Docker made our life very easy as Data Science. Using docker, we can install tools related to
Data science very easily without the hassle of configuration.

This blog is dedicated to installation of Hadoop/Spark environment using Docker images
But before going there, let me introduce you Docker first. So entire section is devided into following
steps:

1. Docker Concept
2. How to install Docker on window
3. Install Spark using docker images

Lets start with Docker

Virtual machine takes long time to boot up and require lots of packages and dependecies to boot up. Linux container(LCX) solve the problem by enabling
multiple isolated environments to run on a single machine.
More info about LCX pleas refer wiki page https://en.wikipedia.org/wiki/LXC

LCX is heart/base of Docker. 






More info on Docker please refer "docker.training"

How to install Docker on window machine. please refer the Docker documentation below
https://docs.docker.com/windows/step_one/

Once docker is up and running fine, please follow below steps to install/run jupyter notebook
1. Click on "Docker Quickstart Terminal"
2. Go to bash sheel (type "bash" and hit return key)
3. On docker terminal run following command
docker run -i -t -h sandbox sequenceiq/spark:1.2.0 /etc/bootstrap.sh -bash
It will take time as firt it will look for spark image on local machine and will start downloading images from docker hub
Please wait untill all images gets downloaded and extracted properly without any error
on sucessful execution of docker run command you will see following messages
$ docker run -i -t -h sandbox sequenceiq/spark:1.2.0 /etc/bootstrap.sh -bash
/
Starting sshd:                                             [  OK  ]
Starting namenodes on [sandbox]
sandbox: starting namenode, logging to /usr/local/hadoop/logs/hadoop-root-nameno
de-sandbox.out
localhost: starting datanode, logging to /usr/local/hadoop/logs/hadoop-root-data
node-sandbox.out
Starting secondary namenodes [0.0.0.0]
0.0.0.0: starting secondarynamenode, logging to /usr/local/hadoop/logs/hadoop-ro
ot-secondarynamenode-sandbox.out
starting yarn daemons
starting resourcemanager, logging to /usr/local/hadoop/logs/yarn--resourcemanage
r-sandbox.out
localhost: starting nodemanager, logging to /usr/local/hadoop/logs/yarn-root-nod
emanager-sandbox.out

Testing of Spark setup 

4. cd /usr/local/spark
5. run "./bin/spark-shell --master yarn-client --driver-memory 1g --executor-memory 1g --executor-cores 1"
6. scala> sc.parallelize(1 to 1000).count()

7. run "./bin/spark-submit  --class org.apache.spark.examples.SparkPi --master yarn-cluster --driver-memory 1g --executor-memory 1g --executor-cores 1 ./lib/spark-examples-1.2.0-hadoop2.4.0.jar


Cloudera Quick start with Docker image

Please follow the steps below.

https://hub.docker.com/r/cloudera/quickstart/

Thursday, December 24, 2015

How to Learn Python

Great source of information and quick start

http://www.pythonlearn.com/

Hive: PARTITIONED BY, DISTRIBUTED BY, SORT BY AND ORDER BY WITH BUCKETTING

1. What is External table in hive. Why external tables should be used over temporary?

External table can be created using the "EXTERNAL" keyword that lets you create a table and provide a LOCATION so that Hive does not use a default location for this table. This helps if you already have data generated. When dropping an EXTERNAL table, data in the table is NOT deleted from the file system. An EXTERNAL table points to any HDFS location for its storage, rather than being stored in a folder specified by the configuration property hive.metastore.warehouse.dir.
This is also called unmanaged tables. Deleting and dropping unmanaged table does not impact on actual datasets Where as default/internal/managed table, if data gets deleted if table got deleted

2. Hive: Difference between PARTITIONED BY, CLUSTERED BY and SORTED BY with BUCKETS.

Concept is clear about why we don partitioning. Its generic concept in database concept. with the help of Partitioning you can manage large dataset by slicing. Resulting high performance of query

Partitionedby: Partitioned table can be created by using PARTITIONED BY clause. A table can have one or more partition column.  Further tables or partition cab be bucketed using CLUSTERED BY columns and data can be stored within bucket via SORT BY columns.

ORDER BY: This gurantees the global ordering of the data using a single reducer. In the strict mode (i.e., hive.mapred.mode=strict), the order by clause has to be followed by a "limit" clause. The limit clause is not necessary if you set hive.mapred.mode to nonstrict. The reason is that in order to impose total order of all results, there has to be one reducer to sort the final output. If the number of rows in the output is too large, the single reducer could take a very long time to finish

Sortedby: Hive uses the columns in SORT BY to sort the rows before feeding the rows to a reducer. The sort order will be dependent on the column types. If the column is of numeric type, then the sort order is also in numeric order. If the column is of string type, then the sort order will be lexicographical order

Hive supports SORT BY which sorts the data per reducer. The difference between "order by" and "sort by" is that the former guarantees total order in the output while the latter only guarantees ordering of the rows within a reducer. If there are more than one reducer, "sort by" may give partially ordered final results.

ClusterBy: Cluster By is a short-cut for both Distribute By and Sort By.
Hive uses the columns in Distribute By to distribute the rows among reducers. All rows with the same Distribute By columns will go to the same reducer. However, Distribute By does not guarantee clustering or sorting properties on the distributed keys.

Bucket: Bucketing is further level of slicing of data. And its allow much more efficient sampling than non-bucketed tables. How does Hive distribute the rows across the buckets? In general, the bucket number is determined by the expression hash_function(bucketing_column) mod num_buckets. The hash_function depends on the type of the bucketing column. For an int, it's easy, hash_int(i) == i. For example, if user_id were an int, and there were 10 buckets, we would expect all user_id's that end in 0 to be in bucket 1, all user_id's that end in a 1 to be in bucket 2, etc.
No of reducer should be equal to no. of buckets. The command set hive.enforce.bucketing = true; allows the correct number of reducers and the cluster by column to be automatically selected based on the table

Creation of bucketed table:
We can create bucketed table with help of CLUSTERED BY clause and optional SORTED BY clause in CREATE TABLE statement


create table bucketed_usertab(
       firstname VARCHAR(64),
        lastname  VARCHAR(64),
        address   STRING,
        city  VARCHAR(64),
)
        COMMENT 'A bucketed sorted user table'
        PARTITIONED BY (country VARCHAR(64))
        CLUSTERED BY (state) SORTED BY (city) INTO 32 BUCKETS
        STORED AS SEQUENCEFILE;


3. Example to insert overwrite with PARTITIONED and CLUSTER BY?

Insert into: Append data
Insert overwrite: Overwrite/replace the data
Inserting data into bucketed table
To insert data into the bucked table, we need to set property hive.enfore.bucketing =true
also we can not directly load bucketed tables with LOAD DATA COMMANDS like partitioned tabled. For loading data in bucketed table we have to use following statement rather LOAD DATA command

set hive.enforce.bucketing = true;

INSERT OVERWRITE TABLE bucketed_usertab PARTITION (country)
        SELECT  firstname ,
        lastname  ,
        address   ,
          city      ,
            country  
        FROM temp_user;


4. Which is most suited to migrate data from SQL Server to HDFS. How to proceed about it. How do we take care of the constraints/joins within the tables?
Using Sqoop we can migrate data from SQL server to HDFS.

For example
sqoop import --query 'SELECT a.*, b.* FROM a JOIN b on (a.id == b.id) WHERE $CONDITIONS' --split-by a.id --target-dir /user/foo/joinresults

Constraints
By default, sqoop-export appends new rows to a table; each input record is transformed into an INSERT statement that adds a row to the target database table. If your table has constraints (e.g., a primary key column whose values must be unique) and already contains data, you must take care to avoid inserting records that violate these constraints. The export process will fail if an INSERT statement fails. This mode is primarily intended for exporting records to a new, empty table intended to receive these results.
syntax
sqoop-export --table foo --update-key id --export-dir /path/to/data --connect ...



5. What is difference between mongodb and cassandra?
Please read at : http://db-engines.com/en/system/Cassandra%3BHBase%3BMongoDB


6. How to access files/directory in shell, that are created in Hue -> Files
Hue files and browser depend on HDFS configuration. Please check what is configuration details you have for name node

you can explore using hdfs commands: hdfs dfs -ls -R /

Tuesday, December 1, 2015

Hadoop Cluster Setup: Best Practice

Operating System Utilities
ssh
HBase uses the Secure Shell (ssh) command and utilities extensively to communicate between cluster nodes. Each server in the cluster must be running ssh so that the Hadoop and HBase daemons can be managed. You must be able to connect to all nodes via SSH, including the local node, from the Master as well as any backup Master, using a shared key rather than a password. You can see the basic methodology for such a set-up in Linux or Unix systems at "Procedure: Configure Passwordless SSH Access". If your cluster nodes use OS X, see the section, SSH: Setting up Remote Desktop and Enabling Self-Login on the Hadoop wiki.
DNS
HBase uses the local hostname to self-report its IP address. Both forward and reverse DNS resolving must work in versions of HBase previous to 0.92.0. The hadoop-dns-checker tool can be used to verify DNS is working correctly on the cluster. The project README file provides detailed instructions on usage.
Loopback IP
Prior to hbase-0.96.0, HBase only used the IP address 127.0.0.1 to refer to localhost, and this could not be configured. See Loopback IPfor more details.
NTP
The clocks on cluster nodes should be synchronized. A small amount of variation is acceptable, but larger amounts of skew can cause erratic and unexpected behavior. Time synchronization is one of the first things to check if you see unexplained problems in your cluster. It is recommended that you run a Network Time Protocol (NTP) service, or another time-synchronization mechanism, on your cluster, and that all nodes look to the same service for time synchronization. See the Basic NTP Configuration at The Linux Documentation Project (TLDP) to set up NTP.
Limits on Number of Files and Processes (ulimit)
Apache HBase is a database. It requires the ability to open a large number of files at once. Many Linux distributions limit the number of files a single user is allowed to open to 1024 (or 256 on older versions of OS X). You can check this limit on your servers by running the commandulimit -n when logged in as the user which runs HBase. See the Troubleshooting section for some of the problems you may experience if the limit is too low. You may also notice errors such as the following:
2010-04-06 03:04:37,542 INFO org.apache.hadoop.hdfs.DFSClient: Exception increateBlockOutputStream java.io.EOFException
2010-04-06 03:04:37,542 INFO org.apache.hadoop.hdfs.DFSClient: Abandoning block blk_-6935524980745310745_1391901
It is recommended to raise the ulimit to at least 10,000, but more likely 10,240, because the value is usually expressed in multiples of 1024. Each ColumnFamily has at least one StoreFile, and possibly more than six StoreFiles if the region is under load. The number of open files required depends upon the number of ColumnFamilies and the number of regions. The following is a rough formula for calculating the potential number of open files on a RegionServer.
Calculate the Potential Number of Open Files
(StoreFiles per ColumnFamily) x (regions per RegionServer)
For example, assuming that a schema had 3 ColumnFamilies per region with an average of 3 StoreFiles per ColumnFamily, and there are 100 regions per RegionServer, the JVM will open 3 * 3 * 100 = 900 file descriptors, not counting open JAR files, configuration files, and others. Opening a file does not take many resources, and the risk of allowing a user to open too many files is minimal.
Another related setting is the number of processes a user is allowed to run at once. In Linux and Unix, the number of processes is set using theulimit -u command. This should not be confused with the nproc command, which controls the number of CPUs available to a given user. Under load, a ulimit -u that is too low can cause OutOfMemoryError exceptions. See Jack Levin’s major HDFS issues thread on the hbase-users mailing list, from 2011.
Configuring the maximum number of file descriptors and processes for the user who is running the HBase process is an operating system configuration, rather than an HBase configuration. It is also important to be sure that the settings are changed for the user that actually runs HBase. To see which user started HBase, and that user’s ulimit configuration, look at the first line of the HBase log for that instance. A useful read setting config on your hadoop cluster is Aaron Kimball’s Configuration Parameters: What can you just ignore?
Example 6. ulimit Settings on Ubuntu
To configure ulimit settings on Ubuntu, edit /etc/security/limits.conf, which is a space-delimited file with four columns. Refer to the man page for limits.conf for details about the format of this file. In the following example, the first line sets both soft and hard limits for the number of open files (nofile) to 32768 for the operating system user with the username hadoop. The second line sets the number of processes to 32000 for the same user.
hadoop  -       nofile  32768
hadoop  -       nproc   32000
The settings are only applied if the Pluggable Authentication Module (PAM) environment is directed to use them. To configure PAM to use these limits, be sure that the /etc/pam.d/common-session file contains the following line:
session required  pam_limits.so
Linux Shell
All of the shell scripts that come with HBase rely on the GNU Bash shell.
Windows
Prior to HBase 0.96, testing for running HBase on Microsoft Windows was limited. Running a on Windows nodes is not recommended for production systems.




Reference: http://hbase.apache.org/book.html#_configuration_files

Monday, November 23, 2015

Lambda & Zeta Architecture for Modern Dataware house

Lamda Architecture

developed by Nathan Marz: it provides a clear set of  architecture of both real time/streaming data and batch processing  work together to provide support for modern DW

Per Lambda architecture, it has three layer which

- Batch layer
- Serving layer
- Speed layer

https://www.mapr.com/solutions/zeta-enterprise-architecture

Sunday, November 15, 2015

Cluster analysis and K-mean clustering

Cluster Analysis

When does use Cluster analysis
1. To figure out what to predict
2. to detect patter of interest in data- when does not know enough what patter to expect
3. As an exploratory tool to understand the data



What is cluster analsys

PCA = Reduce number of cloumns

Cluster analysis = Reduce number of rows

Cluster Analysis:
1. Group objects(typically, rows or records or observations) in a data set based on similarity of the properties or attributes(columns) of the objects(rows)
2. There are at least a few hundred(if not more) approaches for performing cluster analysis


Pupular approaches to cluster Analysis
1. Hierarchical clustering(agglomerative) such as single Linkage, Average Linkage, and Complete linkage clustering

2. Partitioning clustering methods such as K-means and K-Medians for numeric data and K-Models for cluster categorical data
3. Overlapping clustering methods
4. Latent Class methods

K-means cluster
While performing partitioning(K-Means) and overlapping clustering (overlapping k-centroids)
1. Normalize normalize normalize
2. Severe local optima: Run procedure from at least 50 random starts for clustering into K- Groups. Otherwise, there is high risk of sub-optima cluster or groups
3. How many cluster to choose
 a. USe Scree plot and interpret-ability
 b. Don't Link solution don't use it
 c. Unless a population is perfectly multi-model i.e. has exactly K models, once can extract as many cluster as one wants
4. Decide how you would handle missing data- missing values in some variables
 a. Replace missing values in a cloumn by the mean of the non-missing values of each columns
 b. Ignore row entirely if column has missing values

 c. Imput the missing values by predicting modeling techniques




Case study
Assume you are a business analyst in a large finance company operating in the secondary (financial derivatives) market. You have access to their monthly operations database, with 500,000 trades and 200 variables, and are asked to summarize the key patterns and relationships in the data. How would you proceed?

above is centered around the Cluster Analysis topic. I would rather focus to explain the cluster analysis and how K-means clustering can be useful here

Stated problem can be covered under Unsupervized-Classification problem and we can use K-means clustering technique to solve the problem

First let me try to explain the clustering and when does it will be useful.
- To figure out what to predict
- To detect pattern of interest in data when we don have enough what patter to expect
- This can be used as exploratory tool to udernstand the data

Based on the available datasets(500000 trade data with 200 variables), we can use cluster analysis to identify key pattern and relationship in data
and to do the same, here is my approach to procceed
- We will first check the distribution of data if its normal or not
- Using the boxplot will try to detect outlier
- Check if there any outlier or missing values in data
- Treat the outlier/missing values by imputing and/or capping/florring method
- Whole concept is try to normalize data as much as possible
- plot the data using plot() or scree() plot in r and try to identify the possoble group
- Us K-mean cluster create cluster
- Based on the created cluster/group.
- find the mean values of Pricipal components of each group
- Draw the conclustion about the each group for business purpose

Saturday, November 14, 2015

Principal Component/Factor Analysis

When does one use PCA in Predictive Modelling
1. Large number of quantitative predictor variables
a. Hard to understand variables and the patterns of the the interactions in them
b. Hard to figure out which ones to use as predictors-either as main effects or as interactions in the predictive models
2. Improve the overall quality of the predictor variables
a. Prediction in hold out samples can become worse as one adds more predictor variables, especially noisy or correlated variable that add little to enhance the predictive power of the model

3. Reduce the degree-of-relatedness(similarity or correlations) among the variables
a. Moderate to high correlation in prediction results in the difficulty in convergence of solutions of logistic Regression/Multinomial logit models and error in findings coefficients of multiple Liner Regression models
b. Even if models converge, the standard error get inflated, and cause t-value to be lower-resulting in incorrect interpretation of coefficients as not being statistically significant and elimination of variables in models
4. Determine the underlying theme of multiple-measure, complex underlying construct
a. Many variables that are very similar(high co variance or correlation between them) or that measure the same underlying concepts



PCA
Methodology for Predictive Modelling via PCA
1. Perform Principal component analysis in the training sample
2. Retain top performing principal components that accounts for a substantial portion of the variance in data using scree plot
3. Predict the Principal component Scores for the retained components in the hold-out sub-sample
4. Build a logistic regression model to predict churn/stay dependent variable in the training sample using the retained principal components as predictors
5. Perform predictions of churn/stay in the sub-sample of size 2000 using
a. coefficients from the logistic regression model from the previous step and
b. Predict principal component scores from the pricipal components model developed in (3)

What is Principal component analysis
Principal components Analysis is one of the approaches to Factor Analysis that:
- Can be characterized or interpreted as a rotation of the original variables to new set of primary axes(or dimensions)
- Transfers the maximum amount of information from the original set of variables to fewer set of new variables
- Hence it typically results in lower dimensional space composed of the new variables. Hence it is called an approach for lower dimensional representation of the original data
- Variables in new space are called principal components

Principal components are mutually orthogonal

Case Study

***************
Assume you are given a data set with 500,000 observations and 200 variables and are asked to report on (a) the most useful predictive models to build (b) their specifications in terms of dependent and independent variables and (c) their business impact.

How would you use PCA/FA in answering these questions?


Before building predictive model, we have to first think about the followings:

- What are the dependent and independent variables
- What are the pattern or interaction among the variables
- How variables are correlated. Is there multi-collinerity  exits?.

Considering the give case with 500000 observations and 200 variables. We have to deal with following issues:
- Given the large number of variables
a. its hard to find out the pattern among the variables
b. there could be situation of multi coolinarity problem
c. it will be hard to find the most impact-full variables
d. Which are the variables impacting most on predictor variables

Business Impact:
Even if we managed to develop model using the all 200 variables,
- the standard error get inflated
- it can cause t-value to be lower, resulting incorrect interpretation of coefficient

Solution:
We can use PCA as an techniques in FA to overcome the above stated problem
Under PCA,
- we have to rotate the original set of variables to a new set of primary variables/dimension
- Transform the maximum mount of information from the original variables to new fewer set of variables without loosing the value of information
- This is also called lower dimantion representation of the original data and variables in new space are called principal components

Methodlogy to be used under PCA
- Create training and test set of data using 80/20 ratio
- Perform prinicipal component analysis in the training sample
- Ratain the top performing principal components that accounts for substantial portion of the variance in data using scree plot
- Predict the Prinicipal component scores for the ratined components in the test data

Model building:
- Using the retained prinicipal component as predictor, build the model on train est data
- Test model on test data to find the accuracy of the model




Thursday, November 12, 2015

Network Graph

Network Data Analysis: Online University
  1. Load the dataset called studentNetwork.RData. Read the datasets negative-words.txt and positive-words.txt into R. Here is a link: studentNetwork.RDataView in a new window It is also in the Files section
#dir <- "C:/Users/Bhupendra Mishra/Desktop/donotbackup/"
#setwd(dir)
load("C:/Users/Bhupendra Mishra/Desktop/donotbackup/studentNetwork.RData")
#load("studentNetwork.RData")
  1. Make a plot of the network
library(igraph)
## Warning: package 'igraph' was built under R version 3.2.2
## 
## Attaching package: 'igraph'
## 
## The following objects are masked from 'package:stats':
## 
##     decompose, spectrum
## 
## The following object is masked from 'package:base':
## 
##     union
library(statnet)
## Warning: package 'statnet' was built under R version 3.2.2
## Loading required package: network
## Warning: package 'network' was built under R version 3.2.2
## network: Classes for Relational Data
## Version 1.13.0 created on 2015-08-31.
## copyright (c) 2005, Carter T. Butts, University of California-Irvine
##                     Mark S. Handcock, University of California -- Los Angeles
##                     David R. Hunter, Penn State University
##                     Martina Morris, University of Washington
##                     Skye Bender-deMoll, University of Washington
##  For citation information, type citation("network").
##  Type help("network-package") to get started.
## 
## 
## Attaching package: 'network'
## 
## The following objects are masked from 'package:igraph':
## 
##     %c%, %s%, add.edges, add.vertices, delete.edges,
##     delete.vertices, get.edge.attribute, get.edges,
##     get.vertex.attribute, is.bipartite, is.directed,
##     list.edge.attributes, list.vertex.attributes,
##     set.edge.attribute, set.vertex.attribute
## 
## Loading required package: networkDynamic
## Warning: package 'networkDynamic' was built under R version 3.2.2
## 
## networkDynamic: version 0.8.1, created on 2015-10-06
## Copyright (c) 2015, Carter T. Butts, University of California -- Irvine
##                     Ayn Leslie-Cook, University of Washington
##                     Pavel N. Krivitsky, University of Wollongong
##                     Skye Bender-deMoll, University of Washington
##                     with contributions from
##                     Zack Almquist, University of California -- Irvine
##                     David R. Hunter, Penn State University
##                     Li Wang
##                     Kirk Li, University of Washington
##                     Steven M. Goodreau, University of Washington
##                     Jeffrey Horner
##                     Martina Morris, University of Washington
## Based on "statnet" project software (statnet.org).
## For license and citation information see statnet.org/attribution
## or type citation("networkDynamic").
## 
## Loading required package: ergm
## Warning: package 'ergm' was built under R version 3.2.2
## Loading required package: statnet.common
## Warning: package 'statnet.common' was built under R version 3.2.2
## 
## ergm: version 3.5.1, created on 2015-10-18
## Copyright (c) 2015, Mark S. Handcock, University of California -- Los Angeles
##                     David R. Hunter, Penn State University
##                     Carter T. Butts, University of California -- Irvine
##                     Steven M. Goodreau, University of Washington
##                     Pavel N. Krivitsky, University of Wollongong
##                     Martina Morris, University of Washington
##                     with contributions from
##                     Li Wang
##                     Kirk Li, University of Washington
##                     Skye Bender-deMoll, University of Washington
## Based on "statnet" project software (statnet.org).
## For license and citation information see statnet.org/attribution
## or type citation("ergm").
## 
## NOTE: If you use custom ERGM terms based on 'ergm.userterms'
## version prior to 3.1, you will need to perform a one-time update
## of the package boilerplate files (the files that you did not write
## or modify) from 'ergm.userterms' 3.1 or later. See
## help('eut-upgrade') for instructions.
## 
## Loading required package: sna
## Warning: package 'sna' was built under R version 3.2.2
## sna: Tools for Social Network Analysis
## Version 2.3-2 created on 2014-01-13.
## copyright (c) 2005, Carter T. Butts, University of California-Irvine
##  For citation information, type citation("sna").
##  Type help(package="sna") to get started.
## 
## 
## Attaching package: 'sna'
## 
## The following object is masked from 'package:network':
## 
##     %c%
## 
## The following objects are masked from 'package:igraph':
## 
##     %c%, betweenness, bonpow, closeness, components, degree,
##     dyad.census, evcent, hierarchy, is.connected, neighborhood,
##     triad.census
## 
## Loading required package: tergm
## Warning: package 'tergm' was built under R version 3.2.2
## 
## tergm: version 3.3.1, created on 2015-10-25
## Copyright (c) 2015, Pavel N. Krivitsky, University of Wollongong
##                     Mark S. Handcock, University of California -- Los Angeles
##                     with contributions from
##                     David R. Hunter, Penn State University
##                     Steven M. Goodreau, University of Washington
##                     Martina Morris, University of Washington
##                     Nicole Bohme Carnegie, New York University
##                     Carter T. Butts, University of California -- Irvine
##                     Ayn Leslie-Cook, University of Washington
##                     Skye Bender-deMoll
##                     Li Wang
##                     Kirk Li, University of Washington
## Based on "statnet" project software (statnet.org).
## For license and citation information see statnet.org/attribution
## or type citation("tergm").
## 
## Loading required package: ergm.count
## Warning: package 'ergm.count' was built under R version 3.2.2
## 
## ergm.count: version 3.2.0, created on 2015-06-18
## Copyright (c) 2015, Pavel N. Krivitsky, University of Wollongong
##                     with contributions from
##                     Mark S. Handcock, University of California -- Los Angeles
##                     David R. Hunter, Penn State University
## Based on "statnet" project software (statnet.org).
## For license and citation information see statnet.org/attribution
## or type citation("ergm.count").
## 
## NOTE: The form of the term 'CMP' has been changed in version 3.2
## of 'ergm.count'. See the news or help('CMP') for more information.
## 
## 
## statnet: version 2015.11.0, created on 2015-11-04
## Copyright (c) 2015, Mark S. Handcock, University of California -- Los Angeles
##                     David R. Hunter, Penn State University
##                     Carter T. Butts, University of California -- Irvine
##                     Steven M. Goodreau, University of Washington
##                     Pavel N. Krivitsky, University of Wollongong
##                     Skye Bender-deMoll
##                     Martina Morris, University of Washington
## Based on "statnet" project software (statnet.org).
## For license and citation information see statnet.org/attribution
## or type citation("statnet").
## 
## unable to reach CRAN
plot(studentNetwork, main = "Student NEtwork")

  1. How many nodes and edges are there in studentNetwork?
summary(studentNetwork)
## Network attributes:
##   vertices = 205
##   directed = FALSE
##   hyper = FALSE
##   loops = FALSE
##   multiple = FALSE
##   bipartite = FALSE
##  total edges = 203 
##    missing edges = 0 
##    non-missing edges = 203 
##  density = 0.009708274 
## 
## Vertex attributes:
## 
##  Course_of_Study:
##    character valued attribute
##    attribute summary:
##          Business         Fine_Arts      Liberal_Arts Physical_Sciences 
##               109                 4                68                 6 
##        Technology 
##                18 
## 
##  Sex:
##    character valued attribute
##    attribute summary:
##   F   M 
##  99 106 
## 
##  StudentID:
##    integer valued attribute
##    205 values
## 
##  Tweets:
##    character valued attribute
##    attribute summary:
##    the 10 most common values are:
##                                                    abnormal|arbitrary|better-than-expected|dirt-cheap|foolish|lawful|lonesome|pretty|supremely|trump|unconditional|unthinkable 
##                                                                                                                                                                              1 
##                                       abominably|affably|benefit|enchant|enraptured|finagle|fugitive|gleeful|ingenious|nourish|premier|priceless|rapturously|vexingly|wasteful 
##                                                                                                                                                                              1 
##                abominate|adventuresome|affluent|blatantly|conveniently|dummy-proof|hedonistic|idol|improvement|irking|laudable|refresh|rumbling|silent|sweetness|titillatingly 
##                                                                                                                                                                              1 
##                                                                                   abort|altruistically|barbarously|disgruntle|faith|imaginative|indebted|ingenious|unwatchable 
##                                                                                                                                                                              1 
## abound|amenable|anomalous|baffling|dominates|drab|enjoy|flawlessly|happily|humorous|illness|reaffirm|shiny|stupendously|taboo|thoughtfulness|treasure|well-being|well-educated 
##                                                                                                                                                                              1 
##                                                                          abound|clouding|comfortable|expansive|glorious|impartial|principled|reforming|statuesque|troubled|woo 
##                                                                                                                                                                              1 
##                                                                        absurdly|aspiration|brainwash|clear|ergonomical|eye-catch|immaculate|inevitable|nurturing|punk|rumbling 
##                                                                                                                                                                              1 
##                                                                                                       abundant|entranced|hoodwink|outperforms|regress|solemn|thriving|upseting 
##                                                                                                                                                                              1 
##                                              acclaimed|accomplishment|believable|boisterous|breach|flawlessly|fondness|frail|hooray|idolized|peerless|randomly|spew|temptingly 
##                                                                                                                                                                              1 
##                                                                                                       accolade|calming|calumniation|cure|effusively|offending|saint|stupendous 
##                                                                                                                                                                              1 
## 
##  Year:
##    numeric valued attribute
##    attribute summary:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   1.000   1.000   3.000   2.732   4.000   6.000 
## 
## No edge attributes
## 
## Network edgelist matrix:
##        [,1] [,2]
##   [1,]    1   25
##   [2,]    1   52
##   [3,]    1   58
##   [4,]    1   70
##   [5,]    1   87
##   [6,]    1   92
##   [7,]    1   96
##   [8,]    1  100
##   [9,]    1  110
##  [10,]    1  127
##  [11,]    1  151
##  [12,]    1  161
##  [13,]    1  174
##  [14,]    2   52
##  [15,]    2  100
##  [16,]    2  134
##  [17,]    2  190
##  [18,]    5  204
##  [19,]    8   30
##  [20,]    8  104
##  [21,]    8  160
##  [22,]    9   19
##  [23,]    9   54
##  [24,]    9  115
##  [25,]    9  205
##  [26,]   11   44
##  [27,]   11   74
##  [28,]   13   61
##  [29,]   13  153
##  [30,]   14  182
##  [31,]   15   22
##  [32,]   15   55
##  [33,]   15   76
##  [34,]   15  189
##  [35,]   16   40
##  [36,]   16  140
##  [37,]   17  122
##  [38,]   18   63
##  [39,]   18  129
##  [40,]   18  158
##  [41,]   18  195
##  [42,]   21   59
##  [43,]   21  102
##  [44,]   21  140
##  [45,]   22   55
##  [46,]   22   64
##  [47,]   22   76
##  [48,]   22  123
##  [49,]   22  189
##  [50,]   23   36
##  [51,]   25   43
##  [52,]   25   60
##  [53,]   25   77
##  [54,]   25   87
##  [55,]   25   92
##  [56,]   25  147
##  [57,]   27   68
##  [58,]   27   93
##  [59,]   29   51
##  [60,]   29   55
##  [61,]   30   54
##  [62,]   30  104
##  [63,]   30  160
##  [64,]   31  114
##  [65,]   31  185
##  [66,]   32  178
##  [67,]   33  140
##  [68,]   34  187
##  [69,]   34  200
##  [70,]   36   97
##  [71,]   36  167
##  [72,]   38  155
##  [73,]   43   60
##  [74,]   43   77
##  [75,]   44   74
##  [76,]   44  136
##  [77,]   47   74
##  [78,]   47   79
##  [79,]   47  102
##  [80,]   47  105
##  [81,]   47  139
##  [82,]   47  153
##  [83,]   47  189
##  [84,]   47  191
##  [85,]   47  201
##  [86,]   51   55
##  [87,]   51   61
##  [88,]   52  127
##  [89,]   52  190
##  [90,]   53   83
##  [91,]   53  136
##  [92,]   54  115
##  [93,]   55   61
##  [94,]   55   66
##  [95,]   55   86
##  [96,]   55  123
##  [97,]   55  157
##  [98,]   56   71
##  [99,]   56  129
## [100,]   57  133
## [101,]   58  149
## [102,]   59   65
## [103,]   59  104
## [104,]   63  198
## [105,]   64   66
## [106,]   64  123
## [107,]   64  139
## [108,]   64  157
## [109,]   65  104
## [110,]   66   82
## [111,]   66  157
## [112,]   70  158
## [113,]   70  195
## [114,]   74  136
## [115,]   74  176
## [116,]   75  187
## [117,]   75  204
## [118,]   78  137
## [119,]   79   99
## [120,]   79  108
## [121,]   79  164
## [122,]   79  173
## [123,]   81  131
## [124,]   83  136
## [125,]   87   88
## [126,]   87   92
## [127,]   87   96
## [128,]   87  110
## [129,]   87  127
## [130,]   87  156
## [131,]   87  179
## [132,]   87  183
## [133,]   88  183
## [134,]   89  111
## [135,]   89  131
## [136,]   90  117
## [137,]   91  187
## [138,]   92  110
## [139,]   96  100
## [140,]   96  110
## [141,]   96  137
## [142,]   96  150
## [143,]   96  179
## [144,]   98  192
## [145,]   99  164
## [146,]   99  173
## [147,]  100  137
## [148,]  100  150
## [149,]  101  108
## [150,]  102  189
## [151,]  102  201
## [152,]  103  128
## [153,]  103  141
## [154,]  104  160
## [155,]  105  139
## [156,]  108  173
## [157,]  109  121
## [158,]  109  142
## [159,]  110  134
## [160,]  112  185
## [161,]  114  138
## [162,]  114  185
## [163,]  115  144
## [164,]  123  139
## [165,]  123  157
## [166,]  123  178
## [167,]  123  189
## [168,]  124  142
## [169,]  124  160
## [170,]  124  161
## [171,]  125  204
## [172,]  127  150
## [173,]  127  151
## [174,]  129  158
## [175,]  132  150
## [176,]  132  185
## [177,]  134  196
## [178,]  136  202
## [179,]  137  179
## [180,]  138  180
## [181,]  138  185
## [182,]  139  189
## [183,]  139  193
## [184,]  140  160
## [185,]  140  194
## [186,]  142  160
## [187,]  146  192
## [188,]  148  194
## [189,]  149  165
## [190,]  149  186
## [191,]  153  170
## [192,]  158  195
## [193,]  160  166
## [194,]  160  194
## [195,]  161  190
## [196,]  164  173
## [197,]  165  178
## [198,]  165  187
## [199,]  165  199
## [200,]  179  196
## [201,]  181  182
## [202,]  183  190
## [203,]  189  191
Answer: We have total 205 nodes and 203 edges
  1. What are the attributes of this network object? What do they each contain?
Answer: There are four attributes and they contains as follows: 1. Course_of_study(Business, Fine_Arts, Liberal_Arts, Physical_Science, Technology) 2. Sex(F, M) 3. StudentID(205 integer value) 4. Tweets(character values)
5, What proportion of the students are Studying Business? What proportion are in their 2nd Year?
symbol = c(6,5,3,7,4,2)
student.sex = studentNetwork%v%"Sex"
summary(student.sex)
##   F   M 
##  99 106
barplot(table(student.sex), main = "Sex of student", col=symbol)

student.course_study=studentNetwork%v%"Course_of_Study"
summary(student.course_study)
##          Business         Fine_Arts      Liberal_Arts Physical_Sciences 
##               109                 4                68                 6 
##        Technology 
##                18
barplot(table(student.course_study), main="course of study of student", col=symbol)

student.year=studentNetwork%v%"Year"
#View(student.year)
summary(as.character(student.year))
##  1  2  3  4  5  6 
## 62 40 42 25 24 12
barplot(table(student.year), main="Year of study of student", col=symbol)
Write a function that splits the pipe delimited string into a vector of single words, counts which ones are positive and which ones are negative, assigns a score of +1 for each positive word and -1 for each negative word, and sums them for a total score.
#Ceate legend for network graph
symbol.sex=c(4,12) [match(student.sex, c("M","F"))]
symbol.course_study=c(1,2,3,4,5)[match(student.course_study,c("Business", "Fine_Arts", "Liberal_Arts", "Physical_Sciences", "Technology"))]

plot(studentNetwork, vertex.sides = symbol.sex, vertex.rot = 45, vertex.cex = 2, vertex.col = symbol[student.year], edge.lwd = 2, cex.main = 1, displayisolates = TRUE, main = "Network Diagram - Student Year")

legend("bottomright", c("Year1", "Year2", "Year3", "Year4", "Year5", "Year6"), fill = symbol, cex=0.6)
Adjacency matrix: Netword of Nodes and their interconnection can be represented with adjacency matrix The Adjacency matrix of a finete graph G on n vertices is the n x n matrix where the non-diagonal entry a(ij) is the number #of edges from vertex i to vertex j, and the diagonal entry a(ij), depending on convention, is either once or twice the number of edges (loops) from vertex i to itself. Undirected graphs often use the latter convention of counting loops twrice, whereas directed graphs typically use the former convention. There exists a unique adjacency matrix for each isomorphism class of graphs and it is not the adjacency matrix of any other isomorphism class of graphs. In the special case of finite simple graph. The adjacency matrix is a (0,1)-matrix with zeroz on its diagonal. If the graph is undirected, the adjacency matrix is symmetric
Reference: https://en.wikipedia.org/wiki/Adjacency_matrix
#Creating Adjacency Matrix
student.matrix=studentNetwork[,]
Degree: A Node’s degree in an undirected network is defined as its number of edges to other nodes
student.degree<-degree(student.matrix)
student.degree
##   [1] 26  8  0  0  2  0  0  6  8  0  4  0  4  2  8  4  2  8  2  0  6 12  2
##  [24]  0 14  0  4  0  4  8  4  2  2  4  0  6  0  2  0  2  0  0  6  6  0  0
##  [47] 18  0  0  0  6  8  4  6 18  4  2  4  6  4  6  0  4 10  4  8  0  2  0
##  [70]  6  2  0  0 10  4  4  4  2 10  0  2  2  4  0  0  2 20  4  4  2  2  8
##  [93]  2  0  0 14  2  2  6 10  2  8  4 10  4  0  0  6  4 10  2  2  0  6  6
## [116]  0  2  0  0  0  2  2 14  6  2  0 10  2  6  0  4  4  2  6  0 10  8  6
## [139] 12 10  2  6  0  2  0  2  2  2  6  8  4  0  6  0  2  2  8  8  0 16  6
## [162]  0  0  6  8  2  2  0  0  2  0  0  8  2  0  2  0  6  8  2  2  4  6  0
## [185] 10  2  8  0 14  8  4  4  2  6  6  4  0  2  2  2  4  2  0  6  2
  1. Plot a histogram of the scores. What does it indicate?
hist(student.degree, col=symbol, main="Distribution of Nodes' Degree", ylab="Number of Students", xlab="Numbder of Connections")
Betweenness: A deeper measure of network structure is obtained through betweenness. Betweenness is a centrality measure of a node/vertex within a graph Nodes that occur on many shortest paths between other nodes have heigher betweenness than those that do not
student.betweenness <- betweenness(student.matrix)

plot(student.betweenness, col="green", main="Betweenness Centrality", ylab="Betweenness")

n.words <- read.table("C:/Users/Bhupendra Mishra/Desktop/donotbackup//negative-words.txt", header=TRUE, quote="\"")
#View(n.words)
p.words <-read.table("C:/Users/Bhupendra Mishra/Desktop/donotbackup//positive-words.txt", header=TRUE, quote="\"")
#View(p.words)
library(parallel)
library(foreach)
## Warning: package 'foreach' was built under R version 3.2.2
student.tweets=studentNetwork%v%"Tweets"
#student.tweets
tweet.score <- foreach(i=1:205, .combine='rbind') %dopar% 
  {
   words<-unlist(strsplit(student.tweets[i], split ='\\|'))
 #  View(words)
   pos.matches = match(words, unlist(p.words))
  # View(pos.matches)
   neg.matches = match(words, unlist(n.words))
   #View(neg.matches)
   pos.matches = !is.na(pos.matches)
   neg.matches = !is.na(neg.matches)
   score = sum(pos.matches) - sum(neg.matches)
  }
## Warning: executing %dopar% sequentially: no parallel backend registered
hist(tweet.score, main="Sentiment analysis of the Students",xlab="Tweet Score",col=symbol)

#View(tweet.score)
  1. Do the distribution between 2nd Year and 4th Year students look different? How about between those studying Business and those studying Technology?
#Histogram of Tweet Scores for year 1 and year 2 respectively
par(mfrow = c(1,2))
hist(tweet.score[student.year==2], main="Sentiment - Year 2", xlab="Tweet Score", col=symbol)

hist(tweet.score[student.year==4], main="Sentiment - Year 4", xlab="Tweet Score", col=symbol)

#Histogram of Tweets Scorces for Business and Technolgy Students respectively

hist(tweet.score[student.course_study=="Business"], main="Sentiment - Business", xlab="Tweet Score", col=symbol)

hist(tweet.score[student.course_study=="Technology"], main= "Sentiment - Technology", xlab="Tweet Score", col=symbol)