리눅스

 

 - 리눅스 기본 명령어

cafe.daum.net/flowlife/9A8Q/161

 

리눅스 기본 명령어

vmwarehttps://www.vmware.com/kr.html무료사용 제품VMware Workstation Playerhttps://www.centos.org/vmware에 centos 설치 하기https://jhnyang.tistory.com/280https://www.ubuntu-kr.org/1. 데비안(Debian)Debian은

cafe.daum.net

 - 리눅스 기본 편집기 vi/vim 명령어

inpages.tistory.com/124

 

 - 터미널 명령어 실행

pwd						: 사용자의 경로
ls						: 디렉토리
-l						: 자세히 보기
-a						: 숨김파일 확인
-al						: 숨김파일 자세히 보기
~						: 현재 사용자의 경로
/						: 리눅스의 경로
vi aaa					: 파일 생성
esc						: 입력어 대기화면
i, a					: append
shift + space			: 한영
:q!						: 미저장 종료
:wq						: 저장 후 종료
vi bbb.txt				: 파일 생성
리눅스에선 확장자 X
vi .ccc					: 숨김 파일 생성
.						: 숨김 파일
yy		  				: 복사
p 		  				: 붙여넣기
dd        				: 한줄 지우기
숫자+명령어   				: 명령어 여러번 반복
:set nu   				: 줄 번호 넣기
:set nonu 				: 줄 번호 제거
whoami    				: id 확인
s /home					: id 확인
mkdir kbs 				: 디렉토리 생성
mkdir -p  mbc/sbs 		: 상위 디렉토리 자동 생성
cd 디렉토리명 				: 디렉토리 변경
cd ~  					: home으로
cd .. 					: 상위 디렉토리로 이동
rmdir 디렉토리명   			: 디렉토리 삭제
rm 파일명         			: 파일 삭제
rm -rf kbs      		: 파일 있어도 삭제 가능
touch 파일명      			: 빈 파일 생성
cat 파일명        			: 파일 내용 확인
cat 파일명1 파일명2 			: 파일 내용확인
cp 파일명 디렉토리명/ 			: 파일 복사
cp 파일명 디렉토리명/새파일명 	: rename 파일 복사
mv 파일명 디렉토리        	: 파일 이동
rename 파일명 happy 새파일명 : 파일명 변경
mv 파일명 새파일명 			: 파일명 변경
head -3 파일명 			: 앞에 3줄 확인
tail -3 파일명 			: 뒤에 3줄 확인 
more +10 파일명 			: 
grep "검색어" 파일명 		: 검색
grep "[^A-Z]" 파일명* 		: 해당 파일명을 가진 모든 파일에서 대문자가 아닌 값 검색
whereis java 			: 파일 설치 모든 경로
whichis java 			: 파일 설치 경로
ifconfig				: ip 확인
su - root				: super user 접속
su - hadoop				: hadoop 일반 계정에 접속
useradd tom				: tom 일반 계정 만들기
passwd tom				: tom 일반 계정에 암호설정
exit					: 해당 계정 logout
userdel james			: 계정 삭제(logout상태에서)
rm -rf james			: 잔여 계정목록 삭제
-rwxrw-r--				: user, group, others
chmod u-w test.txt		: 현재 사용자에게 쓰기 권한 제거
chmod u-r test.txt		: 현재 사용자에게 읽기 권한 제거
chmod u+rwx test. extxt	: 현재 사용자에게 읽기/쓰기/excute 권한 추가
./test.txt				: 명령어 실행
chmod 777 test.txt		: 모든 권한 다 주기
chmod 111 test.txt		: excute 권한 다 주기
ls -l					: 목록 확인
rpm -qa					: 설치 목록확인
rpm -qa java*			: java 설치 경로
yum install gimp		: 설치
su -c 'yum install gimp': 설치
su -c 'yum remove gimp'	: 제거

 

 - gimp 설치

yum list gi*			: 특정단어가 들어간 리스트
which gimp				: gimp 설치 여부 확인
ls -a /usr/bin/gimp
yum info gimp			: 패키지 정보
gimp					: 실행
wget https://t1.daumcdn.net/daumtop_chanel/op/20200723055344399.png : 웹상에서 다운로드
wget https://archive.apache.org/dist/httpd/Announcement1.3.txt		: 웹상에서 다운로드

 

- 파일 압축

vi aa
gzip aa					: 압축
gzip -d aa.gz			: 압축해제
bzip2 aa				: 압축
bzip2 -d aa.bz2			: 압축해제
tar cvf	my.tar aa bb	: 파일 묶기
tar xvf my.tar			: 압축 해제
java -version			: 자바 버전 확인
su -					: 관리자 접속
yum update				: 패키지 업데이트
rpm -qa | grep java*	: rpm 사용하여 파일 설치
java					: 자바 실행
javac					: javac 실행
yum remove java-1.8.0-openjdk-headless.x86_64	: 삭제
yum -y install java-11-openjdk-devel			: 패키지 설치
rpm -qa | java			: 설치 확인

 

- 이클립스 다운로드

mkdir work				: 디렉토리 생성
cd work
eclipse.org - download - 탐색기 - 다운로드 - 복사 - work 붙여넣기
tar xvfz eclipse tab키	: 압축해제
cd eclipse/
./eclipse
work -> jsou
open spective - java
Gerneral - Workspace - utf-8
Web  - utf-8
file - new - java project - pro1 / javaSE-11 - Don't create
new - class - test / main
sysout alt /
sum inss

 

- FlashPlayer 설치

get.adobe.com/kr/flashplayer 접속

wget ftp://ftp.pbone.net/mirror/www.mde.djura.org/2007.0/RPMS/FlashPlayer-9.0.31.0-1mde2007.0.i586.rpm

rm -f FlashPlayer-9.0.31.0-1mde2007.0.i586.rpm

chmod 777 FlashPlayer-9.0.31.0-1mde2007.0.i586.rpm

rpm -Uvh --nodeps FlashPlayer*.rpm

 

- putty

putty -> ifconfig의 ip -> open -> 예

 

 - centos rpm

www.leafcats.com/171

 

 - CentOS에 MariaDB 설치

cafe.daum.net/flowlife/HqLk/81

 

 - MySql, MariaDB

cafe.daum.net/flowlife/HqLk/63 에서 다운로드
Build path - Configure Buil - Librarie - classpath - AddExternel JARs - apply

 

 - apache server 다운로드

apache.org 접속
맨아래 Tomcat 클릭
Download / Tomcat 10 클릭
tar.gz (pgp, sha512) 다운로드
터미널 창 접속
ls /~다운로드
cd work
mv ~/다운로드.apach ~~ .gz ./
tar xvfz apache-tomcat-10.0.5.tar.gz
cd apache-tomcat-10.0.5/
cd bin/
pwd
./startup.sh							: 서버 실행
http://localhost:8080/ 접속
./shutdown.sh							: 서버 종료
./catalina.sh run						: 개발자용 서버 실행
http://localhost:8080/ 접속
ctrl + c								: 개발자용 서버 종료
cd conf
ls se*
vi server.xml
cd ~
pwd
eclipse 접속
Dynimic web project 생성
이름 : webpro / Targert runtime -> apache 10 및 work - apache 폴더 연결
webapp에 abc.html 생성.
window - web browser - firefox
내용 작성 후 서버 실행.

 

 - R, R Studio Server 설치 및 기타

cafe.daum.net/flowlife/RlkF/11

 

 - R 설치

su - root
yum install epel-release
yum install dnf-plugins-core
yum config-manager --set-enabled powertools
yum install R
R
a <- 10
a
df <- data.frame(value=rnorm(1000, 1, 1))
head(df)
head(df, 3)
q()

 

 - R studio 설치

wget https://download1.rstudio.org/desktop/fedora28/x86_64/rstudio-1.2.5033-x86_64.rpm
rpm -ivh rstudio-1.2.5033-x86_64.rpm
exit
rstudio
install.packages("ggplot2")
library(ggplot2)
a <- 10
print(a)
print(head(iris, 3))
ggplot(data=iris, aes(x = Petal.Length, y = Petal.Width)) + geom_point()

 

 - R studio 서버

vi /etc/selinux/config
SELINUX=permissive으로 수정
reboot
su - root
vi /etc/selinux/config
cd /usr/lib/firewalld/services/
ls http*
cp http.xml R.xml
vi R.xml
port="8787"으로 수정
firewall-cmd --permanent --zone=public --add-service=R
firewall-cmd --reload
https://www.rstudio.com/products/rstudio/download-server/
redhat/centos
wget https://download2.rstudio.org/server/centos7/x86_64/rstudio-server-rhel-1.4.1106-x86_64.rpm
wget https://download2.rstudio.org/server/fedora28/x86_64/rstudio-server-rhel-1.2.5033-x86_64.rpm

yum install --nogpgcheck rstudio-server-rhel-1.4.1106-x86_64.rpm
systemctl status rstudio-server
systemctl start rstudio-server
http://ip addr:8787/auth-sign-in	: 본인 ip에 접속

useradd testuser
passwd testuser
ls /home

mkdir mbc
cd mbc
ls

 

 - 프로그램 셋팅 : ipython, anaconda

cafe.daum.net/flowlife/RUrO/44

주의 : VmWare를 사용할 때는 Virtual Machine Settings에서 Processors를 2 이상으로 주도록 하자. 

 

- anaconda 설치

www.anaconda.com/products/individual

Download - Linux / 64-Bit (x86) Installer (529 MB) - 링크주소 복사

wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh
chmod +x Anaconda~~
./Anaconda~~
q
yes
vi .bash_profile		: 파일 수정
=============================================
PATH=$PATH:$HOME/bin
export PATH

# added by Anaconda3 installer
export PATH="/home/hadoop/anaconda3/bin:$PATH"
==============================================
source .bash_profile
python3
conda deactivate     : 가상환경 나오기
source activate base : 가상환경 들어가기
jupyter notebook
jupyter lab
localhost:8888/tree
ctrl + c
y
jupyter notebook --generate-config
python
from notebook.auth import passwd
passwd()     #sha1 값 얻기
quit()
비밀번호 설정
Verify password 복사
vi .jupyter/jupyter_notebook_config.py		: 파일 수정
ctrl + end
==============================================
c.NotebookApp.password =u'       Verify password 붙여넣기		'
==============================================
quit()
vi .jupyter/jupyter_notebook_config.py
su -
cd /usr/lib/firewalld/services/
cp http.xml NoteBook.xml
vi NoteBook.xml
8001포트 설정
:wq
systemctl status firewalld.service           방화벽 서비스 상태 확인  start, stop, enable
firewall-cmd --permanent --zone=public --add-service=NoteBook
firewall-cmd --reload 
jupyter notebook --ip=0.0.0.0 --port=8001 --allow-root
jupyter lab --ip=0.0.0.0 --port=8001 --allow-root
vi .jupyter/jupyter_notebook_config.py
==============================================
c.NotebookApp.open_browser = False
==============================================

 

 - 하둡 ppt

cafe.daum.net/flowlife/RZ23/24

 : 빅데이터 파일을 여러 대의 서버에 분산 저장(HDFS, Hadoop Distributed File Syetem).

 : 각 서버에서 분산병렬 처리.(MapReduce)

 : 하둡은 데이터 수정불가.

 : sale-out 사용.

 

 - Hadoop 싱글노드로 설치 : Centos 기반 (2020년 기준)

cafe.daum.net/flowlife/RZ23/11

 

 - 하둡 설치

conda deactivate	: 가상환경 나오기
java -version		: 자바 버전 확인
ls -al /etc/alternatives/java	: 자바 경로 확인 후 경로 복사
 => /usr/ ~~ .x86_64 복사
https://apache.org/ 접속 => 맨 밑에 hadoop접속 => Download => 
su -				: 관리자 접속
cd /usr/lib/firewalld/services/	: 특정 port 방화벽 해제
cp http.xml hadoop.xml
vi hadoop.xml					: 파일 수정 후 저장(:wq)
==============================================
<?xml version="1.0" encoding="utf-8"?>
<service>
    <short>Hadoop</short>
    <description></description>
    <port protocol="tcp" port="8042"/>    
    <port protocol="tcp" port="9864"/>
    <port protocol="tcp" port="9870"/>
    <port protocol="tcp" port="8088"/>
    <port protocol="tcp" port="19888"/>
</service>
==============================================
firewall-cmd --permanent --zone=public --add-service=hadoop
firewall-cmd --reload
exit
wget http://apache.mirror.cdnetworks.com/hadoop/common/hadoop-3.2.1/hadoop-3.2.1.tar.gz
tar xvzf hadoop-3.2.1.tar.gz
vi .bash_profile
==============================================
# User specific environment and startup programs
export JAVA_HOME=/usr/ ~~ .x86_64 붙여넣기
export HADOOP_HOME=/home/사용자명/hadoop-3.2.1     
PATH=$PATH:$HOME/.local/bin:$HOME/bin:$HADOOP_HOME/bin:$HADOOP_HOME/sbin  #추가
export PATH
==============================================
source .bash_profile		: .bash_profile을 수정된 내용으로 등록
conda deactivate
ls
cd hadoop-3.2.1/
vi README.txt
vi kor.txt					: 임의 내용 입력
cd etc
cd hadoop
pwd
vi hadoop-env.sh			: 파일 상단에 입력
==============================================
export JAVA_HOME=/usr/ ~~ .x86_64 붙여넣기
==============================================

vi core-site.xml        : 하둡 공통 설정을 기술
==============================================
<configuration>
        <property>
                <name>fs.default.name</name>
                <value>hdfs://localhost:9000</value>
        </property>
      <property>
                 <name>hadoop.tmp.dir</name> 
                       <value>/home/사용자명/hadoop-3.2.1/tmp/</value>
            </property>
</configuration>
==============================================

vi hdfs-site.xml      : HDFS 동작에 관한 설정
==============================================
<configuration>
     <property>
          <name>dfs.replication</name>
          <value>1</value>
     </property>
</configuration>
==============================================

vi yarn-env.sh         : yarn 설정 파일
==============================================
export JAVA_HOME=/usr/ ~~ .x86_64 붙여넣기
==============================================

vi mapred-site.xml      : yarn 설정 파일
==============================================
<configuration>
     <property>
          <name>mapreduce.framework.name</name>
          <value>yarn</value>
     </property>
     <property>
        <name>mapreduce.admin.user.env</name>
        <value>HADOOP_MAPRED_HOME=$HADOOP_COMMON_HOME</value>
    </property>
    <property>
        <name>yarn.app.mapreduce.am.env</name>
        <value>HADOOP_MAPRED_HOME=$HADOOP_COMMON_HOME</value>
    </property>
</configuration>
==============================================

vi yarn-site.xml
==============================================
<configuration>
<!-- Site specific YARN configuration properties -->
     <property>
          <name>yarn.nodemanager.aux-services</name>
          <value>mapreduce_shuffle</value>
     </property>
     <property>
          <name>yarn.nodemanager.aux-services.mapreduce.shuffle.class</name>
          <value>org.apache.hadoop.mapred.ShuffleHandler</value>
     </property>
</configuration>
==============================================

cd					: root로 이동
hdfs namenode -format
hadoop version		: 하둡 버전 확인

ssh					: 원격지 시스템에 접근하여 암호화된 메시지를 전송할 수 있는 프로그램
ssh-keygen -t rsa	: ssh 키 생성. enter 3번.
cd .ssh
scp id_rsa.pub /home/사용자명/.ssh/authorized_keys	: 생성키를 접속할 때 사용하도록 복사함. yes
ssh 사용자명@localhost

start-all.sh		: deprecated
start-dfs.sh
start-yarn.sh
mr-jobhistory-daemon.sh start historyserver	: 안해도됨

jps					: 하둡 실행 상태 확인 - NameNode와 DataNode의 동작여부 확인

stop-all.sh			: deprecated
stop-dfs.sh
stop-yarn.sh

 

http://localhost:9870/ 접속 : Summary(HDFS 상태 확인)
http://localhost:8088/ 접속 : All Applications

 

 - Map/Reduce 처리과정

cafe.daum.net/flowlife/RZ23/17

 

 - 워드 카운트

conda deactivate
cd hadoop-3.2.1/
hdfs dfs -mkdir /test
hdfs dfs -ls/test
hdfs dfs -copyFromLocal ./README.txt /test	: 복사
hdfs dfs -cat /test/README.txt
hadoop jar /home/사용자명/hadoop-3.2.1/share/hadoop/mapreduce/hadoop-mapreduce-examples-3.2.1.jar wordcount /test/README.txt /output			: map/reduce 작업 진행.
hdfs dfs -ls /output						: 목록확인
hdfs dfs -cat /output/part-r-00000
hdfs dfs -ls /
hdfs dfs -rm /output/part*					: 파일삭제
hdfs dfs -rm /output/_SUCCESS
hdfs dfs -rmdir /output

hdfs dfs -put ./kor.txt /test
hadoop jar /home/사용자명/hadoop-3.2.1/share/hadoop/mapreduce/hadoop-mapreduce-examples-3.2.1.jar wordcount /test/kor.txt /daumdata
hdfs dfs -get /daumdata/part* happy.txt		: 하둡에서 파일 가져오기
ls
vi happy.txt

 

 - eclipse + hadoop 연동

conda deactivate
start-dfs.sh
start-yarn.sh
jps
http://localhost:9870/ 접속	: Summary(HDFS 상태 확인)
http://localhost:8088/ 접속	: All Applications
eclipse 실행

 

Tensorflow.js 간단한 예

cafe.daum.net/flowlife/S2Ul/27

 

 * abc.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>tensorflow.js sample</title>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script>

    <script type="text/javascript">
    function abc(){
        // 선형회귀 모델 생성
        const model = tf.sequential();
        model.add(tf.layers.dense({units: 1, inputShape: [1]}));
 
        // 학습을 위한 준비 : 손실 함수와 최적화 함수를 설정
        model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
 
        // 학습 데이터
        const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
        const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
 
        // 데이터를 사용해서 학습
        model.fit(xs, ys).then(() => {
            // 학습된 모델로 결과 예측값 얻기
            pred = model.predict(tf.tensor2d([5], [1, 1]))
            pred.print()    // console로 출력
  document.write('예측값 : ', pred);
        });
    }
    </script>	
</head>
<body>
    결과는 브라우저의 콘솔로 확인하세요.
   <br>
    <button xxxxxxxxxxxxonclick="abc()">클릭</button>
</body>
</html>

 

propertive - javaSE
프로젝트 생성
hadoop_pro
Java1.8
프로젝트 오른쪽 클릭
Configure - Convert to Maven Project

 

* pom.xml

maven.org

hadoop-common 검색
apache
3.2.1
<dependency>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-common</artifactId>
  <version>3.2.1</version>
</dependency>

hadoop-client
apache
3.2.1
<dependency>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-client</artifactId>
  <version>3.2.1</version>
</dependency>

hadoop-hdfs
apache
3.2.1
<dependency>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-hdfs</artifactId>
  <version>3.2.2</version>
</dependency>

hadoop-mapreduce-client-core
apache
3.2.1
<dependency>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-mapreduce-client-core</artifactId>
  <version>3.2.2</version>
</dependency>

 

 - example code download

hadoop.apache.org/

Documentation - 3.2.2

MapReduce
Tutorial
Example: WordCount v1.0 - Source Code

 

src - new - class - pack.WordCount

* WordCount.java

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WordCount {

  public static class TokenizerMapper
       extends Mapper<Object, Text, Text, IntWritable>{

    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {
      StringTokenizer itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        context.write(word, one);
      }
    }
  }

  public static class IntSumReducer
       extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();

    public void reduce(Text key, Iterable<IntWritable> values,
                       Context context
                       ) throws IOException, InterruptedException {
      int sum = 0;
      for (IntWritable val : values) {
        sum += val.get();
      }
      result.set(sum);
      context.write(key, result);
    }
  }

  public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
	
	conf.set("fs.default.name", "hdfs://localhost:9000");
	
    Job job = Job.getInstance(conf, "word count");
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
	
    FileInputFormat.addInputPath(job, new Path("hdfs://localhost:9000/test/data.txt"));
    FileOutputFormat.setOutputPath(job, new Path("hdfs://localhost:9000/out1"));
	System.out.println("success");
	
    //FileInputFormat.addInputPath(job, new Path(args[0]));
    //FileOutputFormat.setOutputPath(job, new Path(args[1]));
	
	System.exit(job.waitForCompletion(true) ? 0 : 1);
  }
}
ls
cd hadoop-3.2.1/
vi data.txt
임의 텍스트 입력
hdfs dfs -put data.txt /test
hdfs dfs -get /out1/part* result1.txt
vi result1.txt
vi vote.txt
임의 텍스트 입력
hdfs dfs -put vote.txt /test

src - new - class - pack2.VoteMapper

 

 * VoteMapper.java

import java.util.regex.*;
import org.apache.hadoop.io.IntWritable
import org.apache.hadoop.io.Text
import org.apache.hadoop.mapreduce.Mapper


public class VoteMapper extends Mapper<Object, Text, Text, IntWritable>{
	private final static IntWritable one =  new IntWritable(1);
	private Text word = new Text();
	
	@Override
	public void map(Object ket, Text value, Context context)throws IOException, InterruptedException{
		String str = value.toString();
		System.out.println(str);
		String regex = "홍길동|신기해|한국인";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		String result = "";
		while(match.find()){
			result += matcher.group() + "";
		}
		StringTokenizer itr = new StringTokenizer(result);
		
		while(itr.hasMoreTokens()){
			word.set(itr.nextToken());
			context.write(word, one);
		}
	}
}

 

src - new - class - pack2.VoteReducer

 

 * VoteReducer.java

public class VoteReducer extends Reducer<Textm IntWritable, Text, IntWritable>{
	private IntWritable result = new IntWritable();
	
	@Override
	public void reduce(Text key, Iterable<IntWritable> values, Context context) throw IOException, InterruptedException{
		int sum = 0;
		for(IntWritable val:values){
			sum += val.get();
		}
		
		result.set(sum);
		context.wrtie(key, result);
	}
}

 

src - new - class - pack2.VoteCount

 

 * VoteCount.java

public class VoteCount{
	public static void main(String[] args) throws Exception{
		Configuration conf = new Configuration();
		conf.set("fs.default.name", "hdfs://localhost:9000");
		
		Job job = Job.getInstance(conf, "vote");
		job.setJarByClass(VoteCount.class);
		job.setMapperClass(VoteMapper.class);
		job.setCombinerClass(VoteReducer.class);
		job.setReducerClass(VoteReducer.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		FileInputFormat.addInputPath(job, new Path("hdfs://localhost:9000/test/vote.txt"));
		FileOutputFormat.setOutputPath(job, new Path("hdfs://localhost:9000/out2"));
		
		System.out.println("end");
		
		System.exit(job.waitForCompletion(true)?0:1);
	}
}

 

hdfs dfs -get /out2/part* result2.txt

'BACK END > Python Library' 카테고리의 다른 글

[Pandas] pandas 정리2 - db, django  (0) 2021.03.02
[MatPlotLib] matplotlib 정리  (0) 2021.03.02
[Pandas] pandas 정리  (0) 2021.02.24
[NumPy] numpy 정리  (0) 2021.02.23

24. 연관분석 : 항목간의 연관 규칙을 발견하는 클러스터링 알고리즘의 일종

install.packages("arules")
library(arules)

 

 - arules가 원하는 transaction format 작성 연습

d_list <- list(c('a', 'b'), c('a', 'c'), c('a', 'e'), c('b', 'c', 'e'))
d_list
names(d_list) <- paste0('tr', c(1:4))
d_list
# $tr1
# [1] "a" "b"
# 
# $tr2
# [1] "a" "c"
# 
# $tr3
# [1] "a" "e"
# 
# $tr4
# [1] "b" "c" "e"
tran <- as(d_list, 'transactions')
tran
inspect(tran)
# items   transactionID
# [1] {a,b}   tr1          
# [2] {a,c}   tr2          
# [3] {a,e}   tr3          
# [4] {b,c,e} tr4

cust <- read.csv("testdata/priori_data2.csv", stringsAsFactors = F)
cust
str(cust)

cust$sangpum[cust$irum=='홍길동']

cust_list <- split(cust$sangpum, cust$irum)
cust_list
# $강감찬
# [1] "감자깡" "새우깡"
# 
# $공기밥
# [1] "자갈치" "맛동산"
# 
# $신기해
# [1] "코코넛" "맛동산"
# 
# $한국인
# [1] "짱구"   "감자깡"
# 
# $홍길동
# [1] "새우깡" "맥주"

cust_tran <- as(cust_list, 'transactions')
cust_tran
inspect(cust_tran)
# items           transactionID
# [1] {감자깡,새우깡} 강감찬       
# [2] {맛동산,자갈치} 공기밥       
# [3] {맛동산,코코넛} 신기해       
# [4] {감자깡,짱구}   한국인       
# [5] {맥주,새우깡}   홍길동  

# 연관규칙 생성
cust_rules <- apriori(cust_tran)
# confidence minval smax arem  aval originalSupport maxtime support minlen maxlen target  ext
# 0.8    0.1    1 none FALSE            TRUE       5     0.1      1     10  rules TRUE

summary(cust_tran)
inspect(cust_rules)
#       lhs         rhs      support confidence coverage lift count
# [1] {자갈치} => {맛동산} 0.2     1          0.2      2.5  1    
# [2] {코코넛} => {맛동산} 0.2     1          0.2      2.5  1    
# [3] {짱구}   => {감자깡} 0.2     1          0.2      2.5  1    
# [4] {맥주}   => {새우깡} 0.2     1          0.2      2.5  1  

customer <- read.csv("testdata/priori_data.csv", stringsAsFactors = F)
customer
#    bunho   irum    sangpum
# 1      1 홍길동     새우깡
# 2      2 홍길동     맛동산
# 3      3 홍길동       맥주
# 4      4 사오정       짱구

customer$sangpum[customer$irum == '홍길동']


customer_list <- split(customer$sangpum, customer$irum)
customer_list

customer_list <- sapply(customer_list, unique) # 중복 제거
customer_tran <- as(customer_list, 'transactions')
customer_tran
summary(customer_tran)

 

 - 정보 획득

itemFrequency(customer_tran) # 구매 빈도 출력
#    감자깡     맛동산       맥주     새우깡     자갈치       짱구 초코칩쿠키 크라운산도     포카칩 
# 0.5000000  0.6666667  0.3333333  0.3333333  0.3333333  0.5000000  0.1666667  0.1666667  0.1666667 
itemFrequency(customer_tran[, 1:3])
itemFrequencyPlot(customer_tran)
itemFrequencyPlot(customer_tran, support = 0.3)
itemFrequencyPlot(customer_tran, topN = 3)

 

 - 연관규칙

customer_rules <- apriori(customer_tran)
summary(customer_rules)

inspect(customer_rules)
inspect(sort(customer_rules, by = "lift")[1:5])
#     lhs                    rhs          support   confidence coverage  lift count
# [1] {크라운산도}        => {포카칩}     0.1666667 1          0.1666667 6    1    
# [2] {포카칩}            => {크라운산도} 0.1666667 1          0.1666667 6    1    
# [3] {맥주,크라운산도}   => {포카칩}     0.1666667 1          0.1666667 6    1    
# [4] {맥주,포카칩}       => {크라운산도} 0.1666667 1          0.1666667 6    1    
# [5] {새우깡,크라운산도} => {포카칩}     0.1666667 1          0.1666667 6    1    
inspect(sort(customer_rules, by = "lift", decreasing = FALSE)[1:5])
inspect(sort(customer_rules, by = "support", decreasing = FALSE)[1:5]) # 지지도

rule_subset <- subset(customer_rules, items %in% c('맛동산', '짱구'))
inspect(rule_subset)
inspect(rule_subset[1:5])
#     lhs                    rhs      support   confidence coverage  lift count
# [1] {초코칩쿠키}        => {맛동산} 0.1666667 1          0.1666667 1.5  1    
# [2] {자갈치}            => {맛동산} 0.3333333 1          0.3333333 1.5  2    
# [3] {자갈치,초코칩쿠키} => {맛동산} 0.1666667 1          0.1666667 1.5  1    
# [4] {맛동산,초코칩쿠키} => {자갈치} 0.1666667 1          0.1666667 3.0  1    
# [5] {자갈치,짱구}       => {맛동산} 0.1666667 1          0.1666667 1.5  1    

 

 - 시각화

install.packages("arulesViz")
library(arulesViz)
plot(customer_rules)
plot(customer_rules, method = "grouped")
plot(customer_rules, method = "graph") # 원 : 연관관계, 원의 크기 : support, 색상진하기 : lift
plot(customer_rules, method = "graph", control = list(type="items"))
plot(customer_rules, method = "graph", engine = 'interactive')

 


# 미국 식료품 매장의 판매자료

data("Groceries")
str(Groceries)
Groceries

gdf <- as(Groceries, 'data.frame')
head(gdf)

library(arules)
rules <- apriori(Groceries, parameter = list(supp=0.001, conf=0.8))
inspect(rules)
plot(rules, method="grouped")

rules <- apriori(Groceries, parameter = list(supp=0.001, conf=0.8, maxlen = 3))
inspect(rules)

rules <- sort(rules, decreasing = T, by='confidence')
inspect(rules)

library(arulesViz)
plot(rules, method = 'graph', control = list(type ='items'))

wmilk <- subset(rules, rhs %in% 'whole milk')
inspect(wmilk)
plot(wmilk, method = 'graph')

oveg <- subset(rules, rhs %in% 'other vegetables')
inspect(oveg)
plot(oveg, method = 'graph')

b_y <- subset(rules, lhs %in% c('butter', 'yogurt'))
inspect(b_y)
plot(b_y, method = 'graph')

22. 비계층적 군집분석 : 군집수를 정해 주고 분석을 진행
 : k-means가 가장 많이 쓰임

iris_s <- scale(iris[-5]) # scale : 표준화 함수를 이용. Species열은 제외
head(iris_s, 3)

 - 군집 개수 결정 후 k-means 모델 작성

install.packages("NbClust")
library(NbClust)
nc <- NbClust(iris_s, min.nc = 2, max.nc = 10, method="kmeans") # nc 클러스터 수

table(nc$Best.nc[1, ])
# 0  2  3  8 10 
# 2 11 11  1  1 
plot(table(nc$Best.nc[1, ]))

iris_k <- kmeans(iris_s, centers = 3, iter.max = 100)
iris_k

names(iris_k)

table(iris_k$cluster)
# 1  2  3 
# 62 50 38
plot(iris_k$cluster, col=iris_k$cluster)

iris$Species2 <- ifelse(iris$Species == 'setosa', 1, iris$Species)
head(iris, 3)
plot(iris$Species2, col=iris$Species2)

 

 - PAM

library(cluster)
iris_pam <- pam(iris_s, 3)
iris_pam
names(iris_pam)
(iris_pam$clustering)
table(iris_pam$clustering) # 교차 분할표
# 1  2  3 
# 50 52 48 
clusplot(iris_pam)

 

21. 군집분석(Clustering) : 비지도학습 - 유클리디안 거리 계산법 사용

 

x <- matrix(1:16, nrow = 4)
x
# [,1] [,2] [,3] [,4]
# [1,]    1    5    9   13
# [2,]    2    6   10   14
# [3,]    3    7   11   15
# [4,]    4    8   12   16
help(dist)
d <- dist(x, method = "euclidean")
d
#   1 2 3
# 2 2    
# 3 4 2  
# 4 6 4 2
plot(d)
text(d, c(LETTERS[1:6]))

txt1 <- read.csv("testdata/cluster_ex.csv")
txt1
# irum kor eng
# 1 홍길동  80  90
# 2 이기자  70  40
# 3 유별나  65  75
# 4 강나루  85  65
# 5 전속력  95  87
plot(txt1[, c(2:3)],
     xlab ='국어',
     ylab ='영어',
     xlim = c(30, 100),
     ylim = c(30, 100),
     main = '학생점수')

text(txt1[, 2], txt1[, 3], labels = abbreviate(rownames(txt1)), cex = 0.8, pos = 1, col = "blue")
text(txt1[, 2], txt1[, 3], labels = txt1[,1], cex = 0.8, pos = 2, col = "red")

dist_m <- dist(txt1[c(1:2), c(2:3)], method = "manhattan")
dist_m
# 1
# 2 60

dist_e <- dist(txt1[c(1:2), c(2:3)], method = "euclidean")
dist_e
# 1
# 2 50.9902

 - 계층적 군집분석

x <- c(1,2,2,4,5)
y <- c(1,1,4,3,5)
xy <- data.frame(cbind(x,y))
plot(xy,
     xlab ='x',
     ylab ='y',
     xlim = c(0, 6),
     ylim = c(0, 6),
     main = '응집적 군집분석')

text(xy[, 1], xy[, 2], labels = abbreviate(rownames(xy)),
     cex = 0.8, pos = 1, col = "blue")
abline(v=c(3), col = 'gray', lty=2)
abline(h=c(3), col = 'gray', lty=2)

 

 - 유클리디안 거리 계산법

dist(xy, method = 'euclidean') ^ 2
#    1  2  3  4
# 2  1         
# 3 10  9      
# 4 13  8  5   
# 5 32 25 10  5

 

 - Dendrogram으로 출력

hc_sl <- hclust(dist(xy) ^ 2, method = "single") # 최단거리법
hc_sl
plot(hc_sl, hang = -1)

hc_co <- hclust(dist(xy) ^ 2, method = "complete") # 완전(최장) 거리법
hc_co
plot(hc_co, hang = -1)

hc_av <- hclust(dist(xy) ^ 2, method = "average") # 평균 거리법
hc_av
plot(hc_av, hang = -1)

par(oma = c(3, 0, 1, 0))
par(mfrow = c(1,3))
plot(hc_sl, hang = -1)
plot(hc_co, hang = -1)
plot(hc_av, hang = -1)


 - 중학생 신체검사 결과

body <- read.csv("testdata/bodycheck.csv")
body
#      번호 악력 신장 체중 안경유무
# 1     1   28  146   34        1
# 2     2   46  169   57        2
# 3     3   39  160   48        2
# 4     4   25  156   38        1
# 5     5   34  161   47        1
# 6     6   29  168   50        1
# 7     7   38  154   54        2
# 8     8   23  153   40        1
# 9     9   42  160   62        2
# 10   10   27  152   39        1
# 11   11   35  155   46        1
# 12   12   39  154   54        2
# 13   13   38  157   57        2
# 14   14   32  162   53        2
# 15   15   25  142   32        1
dim(body)
head(body, 2)

d <- dist(body[, -1]) # 거리계산
d

hc <- hclust(d, method = "complete")
hc
# Cluster method   : complete 
# Distance         : euclidean 
# Number of objects: 15 

plot(hc, hang=-1) # hang=-1 정렬
rect.hclust(hc, k=3, border = "red")

 -  군집별 특징

g1 <- subset(body, 번호 == 10 |번호 == 4 |번호 == 8 |번호 == 1 |번호 == 15)
g2 <- subset(body, 번호 == 11 |번호 == 3 |번호 == 5 |번호 == 6 |번호 == 14)
g3 <- subset(body, 번호 == 2 |번호 == 9 |번호 == 13 |번호 == 7 |번호 == 12)

g1[2:5]
g2[2:5]
g3[2:5]

summary(g1[2:5])
summary(g2[2:5])
summary(g3[2:5])

#Random Forest 분류 모델 나무 구조 모델을 여러 개 합칩 모델(앙상블 기법)

install.packages("randomForest")
library(randomForest)

set.seed(123)
ind <- sample(1:nrow(iris), nrow(iris) * 0.7, replace = FALSE)
train <- iris[ind, ]
test <- iris[-ind, ]

model <- randomForest(formula=Species ~ ., data=train)
model
# randomForest(formula = Species ~ ., data = train) 
# Type of random forest: classification
# Number of trees: 500
# No. of variables tried at each split: 2
# 
# OOB estimate of  error rate: 5.71%
# Confusion matrix:
#   setosa versicolor virginica class.error
# setosa         36          0         0  0.00000000
# versicolor      0         29         3  0.09375000
# virginica       0          3        34  0.08108108

model2 <- randomForest(formula=Species ~ ., data=train, ntree = 200, mtry = 3, na.action = na.omit)
model2
# randomForest(formula = Species ~ ., data = train, ntree = 200,      mtry = 3, na.action = na.omit) 
# Type of random forest: classification
# Number of trees: 200
# No. of variables tried at each split: 3
# 
# OOB estimate of  error rate: 4.76%
# Confusion matrix:
#   setosa versicolor virginica class.error
# setosa         36          0         0  0.00000000
# versicolor      0         30         2  0.06250000
# virginica       0          3        34  0.08108108

model3 <- randomForest(formula=Species ~ ., data=train, ntree = 1000, mtry = 2, na.action = na.omit)
model3

# 모델 성능 향상을 위한 변수 선택, ntree, mtry 설정하기
# 중요 변수

model4 <- randomForest(Species ~ ., data=train, importance = T)
importance(model4) # Petal.Width가 가장 중요한 변수
# setosa versicolor virginica MeanDecreaseAccuracy MeanDecreaseGini
# Sepal.Length  5.947974  9.6040622  7.628999            12.547747         6.743408
# Sepal.Width   4.143228 -0.5277106  7.616918             6.344268         1.895498
# Petal.Length 22.586135 31.0203420 28.842917            34.060288        30.182599
# Petal.Width  21.470279 27.2038165 30.353685            32.467796        30.336028

varImpPlot(model4)

#pred

pred <- predict(model, test)
pred
t <- table(pred, test$Species)
t
# pred         setosa versicolor virginica
# setosa         14          0         0
# versicolor      0         17         0
# virginica       0          1        13

sum(diag(t)) / nrow(test) # 0.9777778

#..
pred4 <- predict(model4, test)
pred4
t4 <- table(pred4, test$Species)
sum(diag(t4)) / nrow(test) # 0.9777778

# ntree, mtry 최적 값 얻기

ntree <- c(400, 500, 600)
mtry <- c(2:4)
param <- data.frame(n=ntree, m=mtry)

for(i in param$n){
  cat('ntree : ', i, '\n')
  for(j in param$m){
    cat('mtree : ', j, '\n')
    model_ir = randomForest(Species ~ ., data=iris, ntree=i, mtry=j, na.action = na.omit)
    print(model_ir)
  }
}

 

'BACK END > R' 카테고리의 다른 글

[R] R 정리 18 - svm, knn  (0) 2021.02.02
[R] R 정리 17 - Naive Bayes  (0) 2021.02.02
[R] R 정리 15 - Decision Tree  (0) 2021.02.02
[R] R 정리 14 - 로지스틱 회귀2 ROC  (0) 2021.02.01
[R] R 정리 13 - 로지스틱 회귀  (0) 2021.02.01

# 분류모델 중 Decision Tree

set.seed(123)
ind <- sample(1:nrow(iris), nrow(iris) * 0.7, replace = FALSE)
train <- iris[ind, ]
test <- iris[-ind, ]

 

# ctree

install.packages("party")
library(party)
iris_ctree <- ctree(formula = Species ~ ., data = train)
iris_ctree
# Conditional inference tree with 4 terminal nodes
# 
# Response:  Species 
# Inputs:  Sepal.Length, Sepal.Width, Petal.Length, Petal.Width 
# Number of observations:  105 
# 
# 1) Petal.Length <= 1.9; criterion = 1, statistic = 97.466
# 2)*  weights = 36 
# 1) Petal.Length > 1.9
# 3) Petal.Width <= 1.7; criterion = 1, statistic = 45.022
# 4) Petal.Length <= 4.6; criterion = 0.987, statistic = 8.721
# 5)*  weights = 25 
# 4) Petal.Length > 4.6
# 6)*  weights = 10 
# 3) Petal.Width > 1.7
# 7)*  weights = 34
plot(iris_ctree, type = "simple")
plot(iris_ctree)

 

# predit

pred <- predict(iris_ctree, test)
pred
t <- table(pred, test$Species) # 인자 : 예측값, 실제값
t
# pred         setosa versicolor virginica
# setosa         14          0         0
# versicolor      0         18         1
# virginica       0          0        12
sum(diag(t)) / nrow(test) # 0.9777778
library(caret)
confusionMatrix(pred, test$Species)
# Confusion Matrix and Statistics
# 
# Reference
# Prediction   setosa versicolor virginica
# setosa         14          0         0
# versicolor      0         18         1
# virginica       0          0        12
# 
# Overall Statistics
# 
# Accuracy : 0.9778          
# 95% CI : (0.8823, 0.9994)
# No Information Rate : 0.4             
# P-Value [Acc > NIR] : < 2.2e-16       
# 
# Kappa : 0.9662          
# 
# Mcnemar's Test P-Value : NA              
# 
# Statistics by Class:
# 
#                      Class: setosa Class: versicolor Class: virginica
# Sensitivity                 1.0000            1.0000           0.9231
# Specificity                 1.0000            0.9630           1.0000
# Pos Pred Value              1.0000            0.9474           1.0000
# Neg Pred Value              1.0000            1.0000           0.9697
# Prevalence                  0.3111            0.4000           0.2889
# Detection Rate              0.3111            0.4000           0.2667
# Detection Prevalence        0.3111            0.4222           0.2667
# Balanced Accuracy           1.0000            0.9815           0.9615

 

# 방법2 : rpart : 가지치기 이용

library(rpart)

iris_rpart <- rpart(Species ~ ., data = train, method = 'class')
x11()
plot(iris_rpart)
text(iris_rpart)

plotcp(iris_rpart)
printcp(iris_rpart)

cp <- iris_rpart$cptable[which.min(iris_rpart$cptable[, 'xerror'])]
iris_rpart_prune <- prune(iris_rpart, cp=cp, 'cp')
x11()
plot(iris_rpart_prune)
text(iris_rpart_prune)

'BACK END > R' 카테고리의 다른 글

[R] R 정리 17 - Naive Bayes  (0) 2021.02.02
[R] R 정리 16 - Random Forest  (0) 2021.02.02
[R] R 정리 14 - 로지스틱 회귀2 ROC  (0) 2021.02.01
[R] R 정리 13 - 로지스틱 회귀  (0) 2021.02.01
[R] R 정리 12 - 다중 선형 회귀 DB  (0) 2021.01.29

11. 다중 회귀 분석 :  독립 변수가 복수 개

 

 - data set

state.x77                          # 미국 50개 주에 대한 dataset
dim(state.x77)                     # 50  8
str(state.x77)
class(state.x77)                   # matrix array
colnames(state.x77)
states <- as.data.frame(state.x77[, c('Murder','Population','Income','Illiteracy', 'Frost')])
str(states)
head(states)
#             Murder Population Income Illiteracy Frost
# Alabama      15.1       3615   3624        2.1    20
# Alaska       11.3        365   6315        1.5   152
# Arizona       7.8       2212   4530        1.8    15
# Arkansas     10.1       2110   3378        1.9    65
# California   10.3      21198   5114        1.1    20
# Colorado      6.8       2541   4884        0.7   166

 

 - 상관계수

# 상관계수
cor(states)
#                Murder Population     Income Illiteracy      Frost
# Murder      1.0000000  0.3436428 -0.2300776  0.7029752 -0.5388834

 

- 다중회귀모델

fit <- lm(Murder ~ Population + Income + Illiteracy + Frost, data=states)
fit
summary(fit) # Multiple R-squared:  0.567

# 값이 5개 이하일 경우 Multiple 사용
# Multiple R-squared과 Adjusted R-squared 차이가 클 경우 data 조정 필요.

par(mfrow=c(2,2))
plot(fit)


- 새로운 모델로 예측값 산출

head(states,3)
part_states <- states[1:3, ]
part_states
pre_statues <- edit(part_states) # 새로운 데이터로 값으로 예측
pre_statues
# Murder Population Income Illiteracy Frost
# Alabama   15.1       6000   6000        0.5     5
# Alaska    11.3       1000   1000        8.9   200
# Arizona    7.8       2212   4530        1.8    15

predict(fit, pre_statues)
# Alabama    Alaska   Arizona 
# 5.037489 38.510170  9.487003 

 

 - 예측 변수 선택 : 다양한 고려가 필요

fit1 <- lm(Murder ~., data=states)
summary(fit1) # Adjusted R-squared:  0.5285

fit2 <- lm(Murder ~ Population+Illiteracy, data=states)
summary(fit2) # Adjusted R-squared:  0.5484

 

 - AIC 통계량 : 최적의 모형의 적합도를 위한 독립변수를 추천
                  : 다수의 모델을 비교할 때 사용

                  : 숫자가 작은 모델이 우수한 모델.

AIC(fit1, fit2)
#     df      AIC
# fit1  6 241.6429
# fit2  4 237.6565

 - 위의 작업을 자동으로 처리하기 - stepwise regression

  1) backward : 모든 변수를 참여시킨 후 기여도가 낮은 것부터 제거하는 방법

full_model <- lm(Murder ~., data=states)
reduced_model <- step(full_model, direction = "backward")
# Start:  AIC=97.75
# Murder ~ Population + Income + Illiteracy + Frost
# 
# Df Sum of Sq    RSS     AIC
# - Frost       1     0.021 289.19  95.753
# - Income      1     0.057 289.22  95.759
# <none>                    289.17  97.749
# - Population  1    39.238 328.41 102.111
# - Illiteracy  1   144.264 433.43 115.986
# => Frost 제거
# Step:  AIC=95.75
# Murder ~ Population + Income + Illiteracy
# 
# Df Sum of Sq    RSS     AIC
# - Income      1     0.057 289.25  93.763
# <none>                    289.19  95.753
# - Population  1    43.658 332.85 100.783
# - Illiteracy  1   236.196 525.38 123.605
# => Income 제거
# Step:  AIC=93.76
# Murder ~ Population + Illiteracy
# 
# Df Sum of Sq    RSS     AIC
# <none>                    289.25  93.763
# - Population  1    48.517 337.76  99.516
# - Illiteracy  1   299.646 588.89 127.311
summary(reduced_model)

 

  2) forward : 유익한 변수부터 하나씩 추가하는 방법

min_model <- lm(Murder ~1, data=states)
fwd_model <- step(min_model, direction = "forward",
                  scop=Murder ~ Population+Income+Illiteracy+Frost, trace = 1) # trace : log
# Start:  AIC=131.59
# Murder ~ 1
# 
# Df Sum of Sq    RSS     AIC
# + Illiteracy  1    329.98 337.76  99.516
# + Frost       1    193.91 473.84 116.442
# + Population  1     78.85 588.89 127.311
# + Income      1     35.35 632.40 130.875
# <none>                    667.75 131.594
# 
# Step:  AIC=99.52
# Murder ~ Illiteracy
# 
# Df Sum of Sq    RSS     AIC
# + Population  1    48.517 289.25  93.763
# <none>                    337.76  99.516
# + Frost       1     5.387 332.38 100.712
# + Income      1     4.916 332.85 100.783
# 
# Step:  AIC=93.76
# Murder ~ Illiteracy + Population
# 
# Df Sum of Sq    RSS    AIC
# <none>                289.25 93.763
# + Income  1  0.057022 289.19 95.753
# + Frost   1  0.021447 289.22 95.759
summary(fwd_model)

- 다중 선형회귀 모델 : iris dataset

head(iris)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa
str(iris)
cor(iris[, -5]) # 범주형 데이터 제외

 

 - train / test로 자료를 분리. 7 : 3
  : 표본의 70% 훈련모델(train), 30% 검증 모델(test)

nrow(iris)   # 150
set.seed(12) # 난수의 시작값 고정
sam_tt <- sample(1:nrow(iris), nrow(iris) * 0.7, replace = F)
sam_tt
NROW(sam_tt)          # 105, NROW() : 배열일 경우 
train <- iris[sam_tt, ]
test <- iris[-sam_tt, ]
dim(train); dim(test)  # 105 5 / 45 5
train
test

 

- 모델 작성

model <- lm(Sepal.Length ~ Sepal.Width+Petal.Length+Petal.Width, data = train) # 학습용 데이터로 모델 작성
options(scipen = 999) # 소수점을 표현
options(scipen = 0)   # E-1
summary(model) # p-value: < 0.00000000000000022

 

 - 선형모델의 만족 조건

# 선형성
aa <- residuals(model)
shapiro.test(aa)              # p-value = 0.8316 > 0.05 이므로 선형성 만족

# 정규성
shapiro.test(model$residuals) # p-value = 0.8316 > 0.05 이므로 정규성 만족

# 독립성(잔차)
install.packages("lmtest")
library(lmtest)
dwtest(model)                 # DW = 2.4964  => 2에 가까울 수록 좋음. 만족.

# 등분산성
install.packages("car")
library(car)
ncvTest(model)                # p = 0.12729 > 0.05 이므로 등분산성 만족

# 다중공선성
model2 <- lm(Sepal.Length ~ Sepal.Width+Petal.Length, data = train)
vif(model2)
vif(model)                    # Petal.Width 14.014160 > 10을 넘으면 다중공선성을 의심해야함.

 

 - 모델평가

pred <- predict(model, test) # test data로 검증
pred[1:3]
# 3        8        9 
# 4.770099 5.048755 4.646646

head(test[,1], 2) # 실제 값              - 4.7 5.0
head(pred, 2)     # 모델에 의한 예측 값  - 4.770099 5.048755

1. 선형 회귀 : 두 변수 간의 선형관계를 파악

: 두 변수는 연속성 데이터
: 두 변수는 상관관계가 있어야 함.
: 두 변수는 인과관계가 있어야 함. 원인(독립변수-x)과 결과(종속변수-y)

 

df <- data.frame(workhour = 1:7, totalpay = seq(10000, 70000, by=10000))
df
#     workhour totalpay
# 1        1    10000
# 2        2    20000
# 3        3    30000
# 4        4    40000
# 5        5    50000
# 6        6    60000
# 7        7    70000
cor(df$workhour, df$totalpay) # 1
plot(totalpay ~ workhour, df)


2. 단순 회귀분석 모형산출

y =wx + b

abcModel <- lm(totalpay ~ workhour, data = df) # lm() : 선형 모델 생성
abcModel #    -5.5e-12(y절편)      1.0e+04(기울기)  

=> y = 1.0e+04 * x -5.5e-12 

predict(abcModel) # 예측값
predict(abcModel, data.frame(workhour=c(2.4, 6.789, 9.4)))
# 1     2     3 
# 24000 67890 94000 

plot(totalpay ~ workhour, data=df)
grid()
abline(abcModel, col="blue", lwd=2) # abline() : 직선 그리기. 


3. 단순선형회귀 모델 작성 연습

head(women, 3)
#height : 독립, weight : 종속
cor(women$height, women$weight) # 0.9954948

plot(weight ~ height, data = women)

 - 모델 작성

fit <- lm(weight~height, data=women)
fit
# (Intercept)       height  
# -87.52         3.45 
# y = 3.45 * height -87.52

 

 - 예측값

pred_y = 3.45 * 60 -87.52
cat('키 60의 예상 몸무게는 ', pred_y) # 95% 신뢰구간
predict(fit, data.frame(height=c(60, 58, 66, 679)))

summary(fit) # 모델에 대한 요약 통계량 확인.
# R-squared:  0.991,	Adjusted R-squared:  0.9903 
# F-statistic:  1433 on 1 and 13 DF,  p-value: 1.091e-14

 => p-value: 1.091e-14 < 0.05 이므로 현재 모델은 신뢰할 수 있다.
      R-squared(상관계수를 제곱, 결정계수 : 모델이 독립변수가 종속변수를 얼마나 잘 설명하는지를 표시한 값)
      1에 가까울 수록 독립변수가 종속변수를 설명을 잘하는 데이터.

 

 - 선형회귀 모델의 적절성을 위한 조건
   :  정규성, 독립성, 선형성, 등분산성 : 잔차의 (분산정도), 다중공선성


 - 시각화로 확인

par(mfrow=c(2,2)) # par() : 그래픽 파라미터 지정, mfrow : 배열 방식지정
plot(fit)

abline(fit)


4. 단순 선형회귀 모델

- 변수 간의 상관관계 확인
  : 상관관계는 있으나 인과관계가 아닌 데이터는 회귀분석으로 알 수 없다

head(iris)
dim(iris)
cor(iris$Sepal.Length, iris$Sepal.Width) # 상관관계
# -0.1175698 => 약한 음의 상관관계
cor(iris$Sepal.Length, iris$Petal.Length)
# 0.8717538 => 강한 양의 상관관계

 

  1) 약한 음의 상관관계로 회귀모델을 생성

result <- lm(formula = Sepal.Length ~ Sepal.Width, data = iris) # 선형모델 생성
summary(result)
# Residuals:
#   Min      1Q  Median      3Q     Max 
# -1.5561 -0.6333 -0.1120  0.5579  2.2226 
# 
# Coefficients:
#   Estimate Std. Error t value Pr(>|t|)    
# (Intercept)   6.5262     0.4789   13.63   <2e-16 ***
#   Sepal.Width  -0.2234     0.1551   -1.44    0.152    
# ---
#   Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# 
# Residual standard error: 0.8251 on 148 degrees of freedom
# Multiple R-squared:  0.01382,	Adjusted R-squared:  0.007159 
# F-statistic: 2.074 on 1 and 148 DF,  p-value: 0.1519

 => 모델 유의성 p value:0.1519 <0.05. 신뢰가능

 

  2) 강한 양의 상관관계로 회귀모델을 생성

result2 <- lm(formula = Sepal.Length ~ Petal.Length, data = iris)
summary(result2)
# Residuals:
#   Min       1Q   Median       3Q      Max 
# -1.24675 -0.29657 -0.01515  0.27676  1.00269 
# 
# Coefficients:
#   Estimate Std. Error t value Pr(>|t|)    
# (Intercept)   4.30660    0.07839   54.94   <2e-16 ***
#   Petal.Length  0.40892    0.01889   21.65   <2e-16 ***
#   ---
#   Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# 
# Residual standard error: 0.4071 on 148 degrees of freedom
# Multiple R-squared:   0.76,	Adjusted R-squared:  0.7583 
# F-statistic: 468.6 on 1 and 148 DF,  p-value: < 2.2e-16

=> p-value: < 2.2e-16

=> p-value가 아주 작다. 신뢰

 


# Spark : 자바를 이용한 데이터 분석 도구
# Scala(스칼라) : 자바를 이용하여 함수형 언어로 제작
# residual(리지듀얼) : 잔차
# Coefficients : 계수
# SSE(explained sum of squares) : 설명된 변동
# SSR (residual sum of squares) : 설명 안된 변동
# SST(Total Sum of Squares) : SSE + SSR

# 설명된 분산 : 종속변수의 분산과 독립 변수 간 교집합.

1. 분산

x <- 1:5
y <- 2:6
x; y
var(x) # var() 분산 - 2.5
var(y) # 2.5

 

2. 공분산 : 관계를 정확하게 알수없음

cov(1:5, 2:6)                          # 2.5
cov(1:5, c(3,3,3,3,3))                 # 0
cov(1:5, 5:1)                          # -2.5
cov(1:5, c(5000,4000,3000,2000,1000))  # -2500

plot(1:5, 2:6)                         # 양의 상관관계
plot(1:5, c(3,3,3,3,3))                # 관계없음
plot(1:5, 5:1)                         # 음의 상관관계
plot(1:5, c(5000,4000,3000,2000,1000)) # 음의 상관관계

 

 

3. 상관계수 : 두 변수간의 분산 관계를 알수 있음.

cor(1:5, 2:6)                          # 1
cor(1:5, c(3,3,3,3,3))                 # 0
cor(1:5, 5:1)                          # -1
cor(1:5, c(5000,4000,3000,2000,1000))  # -1
# file read 후 연습
hf <- read.csv("testdata/galton.csv")
dim(hf) # 898   6
head(hf, 3)
str(hf)
summary(hf)
# 표본 추출 : 아버지(father)와 아들(height)의 키 자료 sampling
hf_man <- subset(hf, sex == 'M') # sex column에서 'M'인 값만
dim(hf_man)                             #465   6
hf_man <- hf_man[c('father','height')] # column이 father, height인 데이터만
dim(hf_man)                             # 465   2
head(hf_man)
# father height
# 1    78.5   73.2
# 5    75.5   73.5
# 6    75.5   72.5
# 9    75.0   71.0
# 11   75.0   70.5
# 12   75.0   68.5
# 수식을 직접 사용하여 공분산 산출
f_mean <- mean(hf_man$father) # 아버지의 키 평균
s_mean <- mean(hf_man$height) # 아들 키 평균
cov_num <- sum((hf_man$father - f_mean) * (hf_man$height - s_mean)) # (아버지키의 편차 * 아들키 편차)의 합
cov_num <- cov_num / (nrow(hf_man)-1) # (아버지키의 편차 * 아들키 편차)의 평균
cov_num # 2.368441
# 내장함수 사용하여 공분산 산출
cov(hf_man$father, hf_man$height)       # 2.368441
# 상관계수
cor(hf_man$father, hf_man$height)       # 0.3913174
plot(height ~ father, data=hf_man, xlable='아버지 키', ylable='아들 키') # 산점도 : 데이터를 점으로 표시
abline(lm(height ~ father, data=hf_man), col='red', lwd=5)
# abline() : 추세선, lm() : 선형 모델, lwd : 선 두께

cor.test(hf_man$father, hf_man$height, method='pearson') #pearson(선형), spearman(범주형), kwndal
# 아버지의 키가 1단위 증가하면, 아들의 키는 0.39 단위 정도 증가 한다고 할 수 있다.
#	Pearson's product-moment correlation
#
#data:  hf_man$father and hf_man$height
#t = 9.1498, df = 463, p-value < 2.2e-16
#alternative hypothesis: true correlation is not equal to 0
#95 percent confidence interval:
# 0.3114667 0.4656805
#sample estimates:
#      cor 
#0.3913174 

4. 상관분석

getwd()
result <- read.csv("testdata/drinking_water.csv", header= TRUE, encoding="UTF-8")
head(result, 3)
# 친밀도 적절성 만족도
# 1      3      4      3
# 2      3      3      2
# 3      4      4      4

summary(result)
var(result$친밀도) # 분산 - 0.9415687
sd(result$친밀도) # 표준편차 - 0.9703446
hist(result$친밀도)

cov(result$친밀도, result$적절성) # 공분산 - 0.4164218
cor(result) # 상관계수
#        친밀도    적절성    만족도
# 친밀도 1.0000000 0.4992086 0.4671450
# 적절성 0.4992086 1.0000000 0.7668527
# 만족도 0.4671450 0.7668527 1.0000000

symnum(cor(result)) # 숫자를 심볼로 표현
# 친 적 만
# 친밀도 1       
# 적절성 .  1    
# 만족도 .  ,  1 
# attr(,"legend")
# [1] 0 ‘ ’ 0.3 ‘.’ 0.6 ‘,’ 0.8 ‘+’ 0.9 ‘*’ 0.95 ‘B’ 1

#상관계수
cor(result$친밀도, result$적절성) # 0.4992086
cor(result$친밀도, result$만족도) # 0.467145
cor(result$적절성, result$만족도) # 0.7668527
cor(result$적절성 + result$친밀도, result$만족도)  # 0.7017394

 

5. corrgram

install.packages("corrgram")
library("corrgram")
help("corrgram")
corrgram(result)
corrgram(result, upper.panel = panel.conf)
corrgram(result, lower.panel = panel.conf)

6. PerformanceAnalytics

install.packages("PerformanceAnalytics")
library(PerformanceAnalytics)
chart.Correlation(result, histogram = , pch="+")

1. web scraping : 한 페이지를 가져옴

install.packages("XML")   # install.packages() : XML 라이브러리 설치
install.packages("httr")  # httr 라이브러리 설치
library(XML)              # library() : 라이브러리 불러오기. pakages tab에서 확인가능
library(httr)             # 라이브러리 불러오기

source <- htmlParse(rawToChar(GET("https://www.melon.com/song/popup/lyricPrint.htm?songId=10000")$content))
# 웹페이지의 전체 html문을 가져온다.

lyrics <- xpathSApply(source, "//div[@class='box_lyric_text']", xmlValue)
# source에서 div의 값을 가져온다.

lyrics <-gsub("[\r\n\t]","",lyrics) # gsub(a,b,c) : c에서 a의 내용을 b로 변경.

 

2. RDMS의 자료 읽기

 - 내장 데이터 베이스 : SQLite

install.packages("rJava")
install.packages("DBI")
install.packages("RJDBC")
install.packages("RSQLite")
library(rJava)
library(DBI)
library(RJDBC)
library(RSQLite)

conn <- dbConnect(RSQLite::SQLite(), ":memory:") # memory : 데이터가 ram상에만 존재
head(mtcars, 3)                                  #default dataset 중 하나
# mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4     21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710    22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
colnames(mtcars)

dbWriteTable(conn, "mtcars", mtcars)    # mtcar 테이블 가져오기
dbListTables(conn)                      # 연결 객체의 테이블 확인 - mtcars
dbListFields(conn,"mtcars")             # 변수 확인

query <- "select * from mtcars"
goodAll <- dbGetQuery(conn, query)      # query 문 실행.
goodAll2 <- dbGetQuery(conn, "select mpg, cyl, disp from mtcars where mpg >= 30")

dbDisconnect(conn)                      # db 객체연결 객체해제

 

 - 원격 DB : sangdata

drv <- JDBC(driverClass = "org.mariadb.jdbc.Driver", classPath = "D:/1. 프로그래밍/0. 설치 Program/mariaDB/mariadb-java-client-2.6.2.jar")
conn <- dbConnect(drv, "jdbc:mysql://127.0.0.1:3306/test","root","123")
conn
dbListTables(conn)

query <- "select * from sangdata"
sangDatas <- dbGetQuery(conn, query)
sangDatas
class(sangDatas) #  data.frame
dim(sangDatas)
nrow(sangDatas)
sangDatas[1:3,]
sangDatas$sang

sangs <- dbGetQuery(conn, "select * from sangdata where sang like '가죽%'")
sangs

# 자료 추가
query <- "insert into sangdata values(10,'신상1', 3, 3500)"
dbSendUpdate(conn, query)           # insert문 실행

df <- data.frame(code =11, sang='볼펜', su=7, dan=2000)
df
dbSendUpdate(conn, "insert into sangdata values(?,?,?,?)", df$code, df$sang, df$su, df$dan)
dbGetQuery(conn, "select * from sangdata")

# 자료 수정
query <- "update sangdata set sang=? where code=11"
dbSendUpdate(conn, query, "컴퓨터") # update문 실행
dbGetQuery(conn, "select * from sangdata")


# 자료 삭제
dbSendUpdate(conn, "delete from sangdata where code =10") # delete문 실행
dbGetQuery(conn, "select * from sangdata")

 

+ Recent posts

12