2015년 1월 29일 목요일

R pivot, R group by order

#R pivot, R group by order

#Grouping 해서 order 한후 원하는 rank뽑아 내기

#문제 x 를 Group으로 그룹핑한 후 각 그룹에 Quantity별로 해당 랭크를 뽑아 나열해라
#  Group Name Quantity
#1     A    v        3
#2     A    u        3
#3     A    w        4
#4     A    x        5
#5     C    x        2
#6     C    y        0

#각 그룹별 2위는?
#답
#  Group Name Quantity
#A     A    w        4
#C     C    y        0

#function is copyed from
#http://stackoverflow.com/questions/14421338/how-do-i-create-order-statistics-by-group-in-r
#author Matthew Plourde

x <- data.frame(Group=c("A","A", "A", "A", "C", "C"),
                Name=c("v", "u", "w","x", "x", "y"),
                Quantity=c(3,3,4,5,2,0))
#  Group Name Quantity
#1     A    v        3
#2     A    u        3
#3     A    w        4
#4     A    x        5
#5     C    x        2
#6     C    y        0

order(x$Quantity, -rank(x$Name))
#[1] 6 5 1 2 3 4
#tail로 뒷 순위에서 부터 랭킹을 가져옴으로 asc로 정렬
in.order <-  function(group) with(group, group[order(Quantity, -rank(Name)), ])
in.order(x)
#  Group Name Quantity
#6     C    y        0
#5     C    x        2
#1     A    v        3
#2     A    u        3
#3     A    w        4
#4     A    x        5

#그냥 적용할 경우 그룹별 랭킹이 나옴
groups.row <- by(x, x$Group, function(group) in.order(group))
groups.row
#x$Group: A
#  Group Name Quantity
#1     A    v        3
#2     A    u        3
#3     A    w        4
#4     A    x        5
#----------------------
#x$Group: C
#  Group Name Quantity
#6     C    y        0
#5     C    x        2

# select 2등
head(tail(groups.row$A,2),1)
#Group Name Quantity
#3     A    w        4

#해당 tail -> head 를 적용
N <- 2
groups.row <- by(x, x$Group, function(group) head(tail(in.order(group),N),1))
#x$Group: A
#  Group Name Quantity
#3     A    w        4
#-----------------------
#x$Group: C
#  Group Name Quantity
#6     C    y        0

#그룹별 랭킹을 하나의 데이터프래임으로 묶기
#rbind(groups.row$A,groups.row$C)
do.call(rbind, groups.row)
#  Group Name Quantity
#A     A    w        4
#C     C    y        0

2015년 1월 27일 화요일

ssh 서버연결

안될때 디버깅 방법
https://help.ubuntu.com/community/SSH/OpenSSH/Keys
서버쪽
sudo service sshd stop
sudo /usr/sbin/sshd -d
클라쪽
ssh -v ( or -vv) username@host's

ssl 접속
로컬
cd ~/.ssh
ssh-keygen -t rsa -C "resoliwan@gmail.com"
vi id_rsa.pub

복사

서버 접속
cd ~/.ssh
authorized_keys 있으면
cp authorized_keys back_up_authorized_keys
authorized_keys 없으면
cat id_rsa.pub >> authorized_keys
chmod go-w ~/
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

vi authorized_keys 또는 cat id_rsa.pub >> authorized_keys
위에 펍키 그냥 추가하기

authorized_keys 권한이 아래와 같은지 확인
-rw------- 1 usreId usreId 1247 2015-01-28 14:18 authorized_keys

.ssh/config
아래와 같이 설정을 추가해서 쓸수 있음
Host ipaddress
HostName ipaddress
User usreId
identityFile ~/.ssh/self


ssh 서버 설정하기(리무트)
[서버에서]
/etc/ssh/sshd_config
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key


RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile      .ssh/authorized_keys
//RSAAuthentication, PubkeyAuthentication을 허용하며  각 유저의 .ssh/authorized_keys 파일에
공개키를 저장하겠음

PasswordAuthentication yes
위에 실패할경우 패스워드 접속을 하겠음

* 옵션별 상세 설명
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
설명
Specifies a file containing a private host key used by SSH.  The
    default is /etc/ssh/ssh_host_key for protocol version 1, and
    /etc/ssh/ssh_host_dsa_key, /etc/ssh/ssh_host_ecdsa_key,
    /etc/ssh/ssh_host_ed25519_key and /etc/ssh/ssh_host_rsa_key for
    protocol version 2.

    사용이유
   To prevent man-in-the-middle attacks, each SSH server has a unique identifying code, called a host key. These keys prevent a server
   from forging another server’s key. If you connect to a server for the first time or if the server presets a different key then
   previously, WinSCP will prompt you to verify the key.

RSAAuthentication yes
RSA 인증을 설정. Protocol 1 에 적용

PubkeyAuthentication yes
공개키 인증 설정. Protocol 2에 적용

AuthorizedKeysFile
공개키 파일명 파일명을 지정
디폴트는 유저의 홈 디렉토리로부터의 상대 패스에서 AuthorizedKeysFile 에 설정되 있는 파일을 공개키 파일로 설

서비스 재시작
service sshd restart

로컬에서 키생성
[로컬에서]
ssh-keygen -t dsa
Enter file in which to save the key (/Users/lee/.ssh/id_dsa):  enter
이름을 지정하면 키 복사시 ssh-copy-id -i path/to/key_name.pub user_name@host_name
연결시 ssh -i path/to/key_name user@host
로 접속 해야 한다.



키 파일 서버에 올리기
[로컬에서]
scp -P 포트 로컬파일 리무트계정@리무트주소:리무트파일

어떻게 동작하는지 알고 싶으면 아래 링크 확인
http://www.parkjonghyuk.net/lecture/modernCrypto/lecturenote/chap05.pdf

2015년 1월 6일 화요일

genetic algorithm

genetic algorithm
  글로벌 또는 로컬 최적점을 찾기 위해 사용하는 알고리즘

자연선택설에서 아이디어를 빌려온 알고리즘
  생물이 환경에 적합하면 살아남아 서로의 유전 형질을 이어 받은 자식을 남긴다.
  또한 가끔씩 돌연변이가 발생한다.

  세대가 지나감에 따라 자연선택설에 의해 환경에서 가장 적합한 자식이 살아남든다.
  이 자식이 가장 글로벌 최적값에 가깝다 라는 가정

  예를 들어보자
  한종의 여러 객체들이 존재한다. 그리고 특징을 각인덱스의 숫자라고 할때
  s1, s2.... sn
  [1,2,3,5,6,8],[4,5,6,7,8,9]....
  생물이 환경에 적합성을 평가하는 공식 을 e()라고 하자(적합할수록 높은 점수)
  각 객체들을 e(s1)에 집어 넣은 후 정렬하여 탑 10을뽑는다.

  이후 살아남은 객체 들중 교배
    [1,2,3,5,6,8],[4,5,6,7,8,9] -> [1,2,3,7,8,9]= 부모1 중 앞에꺼 3개  부모2중 뒤에꺼 3개
  확률에 의해서 가끔 돌연변이
    [1,2,3,5,6,8] -> [0,2,3,5,6,8] 맨앞의 특성이 조금 변화함
  이가 발생하고 세대가 지나가면

  위를 계속반복함
  세대가 지나감에 따라 가장 환경에 적합한 객체만 생존한다.


def geneticoptimize(domain,costf,popsize=50,step=1, mutprod=0.2,elite=0.2,maxiter=100):
  # Mutation Operation
  def mutate(vec):
    i=random.randint(0,len(domain)-1)
    if random.random()<0.5 and vec[i]>domain[i][0]:
      return vec[0:i]+[vec[i]-step]+vec[i+1:]
    elif vec[i]<domain[i][1]:
      return vec[0:i]+[vec[i]+step]+vec[i+1:]

  # Crossover Operation
  def crossover(r1,r2):
    i=random.randint(1,len(domain)-2)
    return r1[0:i]+r2[i:]

  # Build the initial population
  pop=[]
  for i in range(popsize):
    vec=[random.randint(domain[i][0],domain[i][1])
          for i in range(len(domain))]
    pop.append(vec)
  # How many winners from each generation?
  topelite=int(elite*popsize)
  # Main loop
  for i in range(maxiter):
    scores=[(costf(v),v) for v in pop] scores.sort( )
    ranked=[v for (s,v) in scores]
    # Start with the pure winners
    pop=ranked[0:topelite]
    # Add mutated and bred forms of the winners
    while len(pop)<popsize:
    if random.random()<mutprob:
      # Mutation
      c=random.randint(0,topelite)
      pop.append(mutate(ranked[c]))
    else:
      # Crossover
      c1=random.randint(0,topelite)
      c2=random.randint(0,topelite)
      pop.append(crossover(ranked[c1],ranked[c2]))
    # Print current best score
    print scores[0][0]
  return scores[0][1]

Simulated Annealing

Simulated Annealing
로컬 최적점을 피하기위해 사용하는 최적점 휴레스틱 알고리즘

주어진 시간에(자원에) 최선을 다한 글로발 최적점을 찾기위해 사용
(정획히 글로발 최적점을 찾기위해 모든 가능성을 계산하는게 아니라 주어진 자원만큼만 계산함)

컨셉 :철을 강화하기 위해 열을 높이고 식이는 담금질 기법에서 아이디어를 차용함
temp라는 온도 변수 높은 값에서 --> 낮은값으로
s (현재파라미터), s'(비교파라미터), E() 결과 함수

기본적으로 현재값 E(s)보다 비교값 E(s')이 작을때 비교파라미터 s' 을 현재 파라미터로 s 로 변경하나
로컬 최적점을 피하기 위해서 확률을 사용해 반대의 경우에도 변경하는경우가 있다(T가 높을때 반대의 경유로 변경하는일이 자주 발생)

동작방법

while temp > 0
if(E(s') < E(s)) prob =  1
else prob = exp(-(E(s')-E(s))/T)

if(random.float() < prob) s = s'

temp--;

return s

위 함수를 보면 temp 가 0이될때까지 계산한다(주어진 자산만큼)
E(s') < E(s) 이면 prob = 1
만약 비교 파라미터가 이전 파라미터보다 크면 무조건 비교 파라미터로 변경
그렇지 않다면 exp(-(E(s')-E(s))/T)
비교 값이 현재 값보다 작기 때문에 크기 때문에 -(E(s')-E(s)) 은 무조건 양수
최초 T 가 크면 exp(0)에가까워지고 확률은 1이 나올 가능 성이 높아진다.
(현재값보다 비교값이 크지만 로컬 옵티마를 피하기 위해 변경 하는 경우)
하지만 T 가 작아질수록 1에 비해 상대적으로 작은 값이 나올 확률이 점점 높아 진다