R에서 연산자 Overloading

이미지
객체지향 프로그램언어는 다음과 같은 특징을 갖고 있다.   1. Encapsulation   2. Information Hiding   3. Abstraction   4. Inheritance   5. Polymorphism 쉽지 않은 개념이라 OOPL을 배우면서 힘들어하는 부분이다. 이 중에서 호불호가 있는 Polymorphism의 연산자 다형성을 간단히 살펴보자. Polymorphism(다형성)이란 서로 다른 클래스의 객체가 같은 메시지를 받았을 때 각자의 방식으로 동작할 수 있는 기능을 이야기한다. 이러한 다형성은 Overriding과 Overloading으로 구현이 되는데, 먼저 Overriding은 상속받은 함수를 재정의하여 사용할 수 있는 기능을 이야기한다. 그리고 Overloading은 같은 함수나 연산자라도 인수에 따라 다른 기능을 하는 것을 말한다. 예를 들어, 일반적으로 "+" 는 좌우측 Operand를 합하는 연산자지만, 빼거나 곱한 결과를 가져올 수 있게 연산자 Overloading을 할 수 있다. 처음 이야기를 들으면 쓸데없는 기능이라고 생각될 수 있지만, 객체지향을 구현하는 입장에서는 매우 강력한 기능일 수 있다. R 언어에서도 쉽게 연산자 Overloading을 구현할 수 있다.   `%+%` <- function(x, y) { paste0(x, y) } 이렇게 함수를 정의하고,   "대한" %+% "민국" 라고 실행을 하면,   "대한민국" 으로 결과가 나온다. 편리한 연산자 Overloading이지만 절제된 사용이 필요하다. by 윤석용 Ph.D @ 2020.5.26

Systematic Sampling in R

SampleBy in the doBy package that was useful in R is not supported. I have created sample.by systematic sampling function as below. ^^ ## usage : sample.by(data_as_dataframe, number_of_column, ratio_of_sample) ##             returns a list of sample.df and rest.df   sample.by <- function(df, by.col.loc=1, prop=0.1) {   sample.df <- data.frame()   rest.df <- data.frame()   dat <- split(df, df[by.col.loc])   for(i in 1:NROW(dat)) {     idx <- sample(c(rep(1,n<-round(NROW(dat[[i]]) * prop)),                     rep(2,NROW(dat[[i]]) - n)))     sample.df <- rbind(sample.df, dat[[i]][idx==1,])     rest.df  <- rbind(rest.df, dat[[i]][idx==2,])       }   list(sample.df=sample.df[sample(NROW(sample.df)),],        rest.df=rest.df[sample(NROW(rest.df)),]) } ## example sample.by(iris, 5, 0.7) 

ubuntu server에 GUI 설치

GUI 버전설치 Ubuntu Desktop : sudo apt install ubuntu-desktop KDE : sudo apt install kubuntu-desktop XFCE : sudo apt install xface LXDE : sudo apt install lxde Openbox : sudo apt install openbox 기본프로그램 제외한 최소설치 $ sudo apt install --no-install-recommends ubuntu-desktop

ipython notebook에서 다른 버전의 python 설치

1. Anaconda 5 설치 2. Python 2.7 환경구축     $ conda create -n python27 python=2.7     $ source activate python27     $ conda install notebook ipykernel     $ ipython kernel install --user 3. Python 3.5 환경구축     $ conda create -n python35 python=3.5     $ source activate python35     $ conda install notebook ipykernel     $ ipython kernel install --user 4. $ ipython notebook ./local/share/jupyter/kernels 내 환경변수로 수정가능   

Tensorflow의 SSE관련 에러

새로 컴파일하면 해결되지만...귀차니즘이 발동할때는 아래처럼. ^^ import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf

Remote 서버의 Jupyter Notebook 사용하기

Jupyter Notebook을 이용하여 원격 서버의 Python, R 등을  로컬 PC의 웹브라우저로 접속하는 방법입니다. 1. Remote PC Console $ jupyter notebook --no-browser --ip=192.168.25.1 2. Local PC Web Browser http://192.168.25.1:8888 ** R을 multi kernel로 설정하려면... (상세한 설정은 지난 게시글 참조)     $ sudo apt install libzmq3-dev      > install.packages(c('crayon', 'pbdZMQ', 'devtools'))     > devtools::install_github(paste0('IRkernel/', c('repr', 'IRdisplay', 'IRkernel')))     > IRkernel::installspec()

Python의 Tensorflow 코드를 R로 변환

"First Contact with Tensorflow"의 Regression Python 코드를 R 코드로 되도록이면 1:1로 변경해 보았습니다. Python 코드 import numpy as np num_points = 1000 vectors_set = [] for i in xrange(num_points):   x1= np.random.normal(0.0, 0.55)   y1= x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)   vectors_set.append([x1, y1]) x_data = [v[0] for v in vectors_set] y_data = [v[1] for v in vectors_set] import matplotlib.pyplot as plt plt.plot(x_data, y_data, 'ro') plt.legend() plt.show() import tensorflow as tf W = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) b = tf.Variable(tf.zeros([1])) y = W * x_data + b loss = tf.reduce_mean(tf.square(y - y_data)) optimizer = tf.train.GradientDescentOptimizer(0.5) train = optimizer.minimize(loss) init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) for step in xrange(8):   sess.run(train)   print(step, sess.run(W), sess.run(b))   print(step, sess.run(loss))   plt.plot(x_data, y_data, 'ro')   plt.plo