기본 콘텐츠로 건너뛰기

12월, 2021의 게시물 표시

통계관련 함수와 메서드 사전

A B C d E F G H I K L M N O P Q R S T U V W Z A statsmodels.ap.stats.anova_lm(x) statsmodels.formula.api.ols 에 의해 생성되는 모형 즉, 클래스 인스턴스(x)를 인수로 받아 anova를 실행합니다. np.argsort(x, axis=-1, kind=None) 객체 x를 정렬할 경우 각 값에 대응하는 인덱스를 반환합니다. Axis는 기준 축을 지정하기 위한 매개변수로서 정렬의 방향을 조정할 수 있음(-1은 기본값으로 마지막 축) pandas.Series.autocorr(lag=1) lag에 전달한 지연수에 따른 값들 사이의 자기상관을 계산 B scipy.stats.bernoulli(x, p) 베르누이분포에 관련된 통계량을 계산하기 위한 클래스를 생성합니다. x: 랜덤변수 p: 단일 시행에서의 확률 scipy.stats.binom(x, n, p) 이항분포에 관련된 통계량을 계산하기 위한 클래스를 생성합니다. x: 랜덤변수 n: 총 시행횟수 p: 단일 시행에서의 확률 C scipy.stats.chi2.pdf(x, df, loc=0, scale=1) 카이제곱분포의 확률밀도함수를 계산 $$f(x, k) =\frac{1}{2^{\frac{k}{2}−1}Γ(\frac{k}{2})}x^{k−1}\exp\left(−\frac{x^2}{2}\right)$$ x: 확률변수 df: 자유도 pd.concat(objs, axis=0, join=’outer’, …) 두 개이상의 객체를 결합한 새로운 객체를 반환. objs: Series, DataFrame 객체. Axis=0은 행단위 즉, 열 방향으로 결합, Axis=1은 열단위 즉, 행 방향으

미적분의 기본 용어

내용 기본 용어 정의 상수와 변수 함수, 변화율, 그리고 미분 양함수와 음함수 기본 용어 정의 미적분을 시작하는 과정에 처음으로 만나는 장벽은 사용되는 기호에서 기인하는 경우가 많습니다. 그러므로 미적분에서 필수적으로 사용되는 몇몇의 용어를 소개합니다. d 는 단지 ' 조금 ' 또는 ' 약간 '을 의미합니다. 이 의미가 좀 모호하기는 하지만 전체에서 아주 작은 부분, 좀더 정확히는 무한히 작은 부분을 나타내기 위해 사용합니다. 그러므로 dx는 x의 조금, du는 u의 조금이라는 의미입니다. $\mathbf{\int}$(integral)은 합계 sum의 첫 글자인 s를 길게 늘어뜨린 형태입니다. 그러므로 $\int\, dx$는 x의 작은 부분들의 합을 의미합니다. 이것을 적분 이라고 합니다. 예로서 1시간은 3600초의 합입니다. 적분기호를 사용하면 다음과 같이 나타낼 수 있습니다. $$\int \text{sec} = \int ds = \text{hour}$$ '작음' 또는 '조금'을 나타내는 d는 상대적입니다. 예를 들어 1시간은 60분으로 구성되며 1시간에 비해 1분은 작은양입니다. 그러나 그보다 1초는 더 작은 양이 됩니다. 어떤 부분에서는 '작다'보다는 '미세하다'라고 나타낼 수 있습니다. 상수와 변수 미적분학에서 모든 수는 상수(constant) 와 변수(variable) 로 구분합니다. 예를 들어 갓 태어난 아기의 신장이 50cm이고 이후 아기의 성장을 기록한다고 해봅니다. 이 경우 50은 변할 수 없는 수인 상수가 되며 지속적인 성장에 의해 50에 첨가되는 수는 계속 변할 것입니다. 이렇게 지속적으로 변하는 수를 변수라고 합니다. 수학에서 수는 알파벳을 기호화하여 사용합니다. 위의 예에서 상수인 50을 a로 하고 이 값에 더해지는 변수를 x로 하여 다음과 같

Time 변수 조정

내용 date 인덱스의 분리 순환적 시간 특성 One-hot Encoding get_dummies()적용 sklearn.preprocessing.OneHotEncoder 클래스 사용 torch.functional.one_hot() 함수 사용 Time 변수 조정 date 인덱스의 분리 Pandas DataFrame 객체에서의 시간 인덱스는 DateTime 객체인 Pandas의 DatetimeIndex 유형입니다. 물론 string의 시간(날짜)등 역시 이 자료형으로 전환할 수 있습니다. 그러므로 다음과 같이 인덱스 값에서 년, 월, 일과 같은 새로운 feature을 쉽게 생성할 수 있습니다. pd객체.index.year: 인덱스 중 년을 추출 pd객체.index.month: 인덱스 중 월 추출 pd객체.index.day: 인덱스 중 일을 추출 pd객체.index.weekday: 인덱스 중 일을 요일로 변경하여 반환 import FinanceDataReader as fdr st=pd.Timestamp(2021, 1, 1) et=pd.Timestamp(2021, 12, 27) data=fdr.DataReader("KS11", st, et) data.tail(3) Close Open High Low Volume Change Date 2021-12-23 2998.17 2998.02 3000.70 2980.91 483840000.0 0.0046 2021-12-24 3012.43 3009.48 3025.77 3009.48 537550000.0 0.0048 2021-12-27 2999.55 3013.94 3017.31 2999.30 475360000.0 -0.0043 time=data.index time DatetimeIndex(['2021-01

Pipeline_python

Pipeline은 여러개의 측정자들(모형 클래스)을 하나로 연결하기 위해 사용할 수 있습니다. 이것은 데이터의 처리 과정 예를 들어 feature selection, normalization and classification 등의 과정을 고정된 연속 단계로 묶어서 처리 할 경우 사용됩니다. estimators = [('OLS', LinearRegression()), 'Theil-Sen', TheilSenRegressor(random_state=42)), ('RANSAC', RANSACRegressor(random_state=42)), ('HuberRegressor', HuberRegressor())] estimators객체는 여러가지 모형 클래스 객체를 각각의 이름과 함께 저장합니다. for name, estimator in estimators: model = make_pipeline(PolynomialFeatures(3), estimator) model.fit(this_X, this_y) 위의 model 객체는 estimators의 각 클래스 객체에 3차 변수 즉, 원래의 각 변수를 3제곱한 값과 각 변수간의 교호작용에 대한 새로운 변수들을 생성하는 함수인 PolynomialFeatures(3)을 결합시킵니다. 이 함수의 3은 차수 즉, order=3을 의미합니다.

데이터 분석을 위한 금융자료 I

내용 결측치 조정 표준화 tensor 형으로 전환 batch sample 생성 주가가료 FinanceDataReader 모듈을 사용하여 다양한 금융자료를 호출할 수 있습니다. 이 호출된 자료는 pandas.DataFrame 형으로 분석 툴에 적합한 자료형으로 변환이 필요합니다. 다음은 kospi에 대한 자료를 호출한 것입니다. import FinanceDataReader as fdr st=pd.Timestamp(2000,1, 1) et=pd.Timestamp(2021, 12, 27) data=fdr.DataReader("KS11", st, et) data.tail(3) Close Open High Low Volume Change Date 2021-12-23 2998.17 2998.02 3000.70 2980.91 483840000.0 0.0046 2021-12-24 3012.43 3009.48 3025.77 3009.48 537550000.0 0.0048 2021-12-27 2999.55 3013.94 3017.31 2999.30 462900.0 -0.0043 위 결과와 같이 호출된 주가자료를 Close, Open, High, Low, Volume, Change(종가, 시가, 고가, 저가, 거래량, 변화율)등으로 구성되어 있습니다. 위와 같은 지수와 개별종목의 경우 가격의 순서에서 차이가 납니다. 예를 들어 삼성전자의 경우 변수의 나열순서가 시가, 고가, 저가, 종가, 거래량, 변화율 순으로 나타냅니다. 이러한 차이는 이후 자료의 조정에서 유의되어야 할 부분입니다. 위 자료중 change는 전날 거래 종료 이후에 일어나는 거래의 변화를 나타냅니다. 위 자료를 기반으로 하는 분석자료는 다음과정을 통해 이루어집니다. 물론 이 과정은 유연한 것이며 다른 방법으로 대체할 수 있습니다. 다음 과정은 4번 이후

활성함수

내용 시그모이드함수(Sigmoid function) ReLU 함수 하이퍼볼릭탄젠트함수 활성함수(activation function) 활성함수는 가중치 합계를 계산하고 여기에 편향을 추가하여 뉴런의 활성화 여부를 결정합니다. 즉, 이 함수를 통과하면서 선형함수의 결과를 비선형으로 전환됩니다. 선형함수는 입력과 출력사이에 상수배의 관계를 의미합니다. 즉, 동일한 변화를 가지는 것으로 직선의 형태를 보이지만 비선형은 직선으로 표시할 수 없습니다. 선형함수의 반복은 그 관계를 변화시킬 수 없으므로 입력 층에 대한 신호의 변화를 명확히 하기 위해 비선형 함수 즉, 활성함수를 사용하여야 합니다. 결과적으로 활성화 함수는 미분가능한 비선형 결과를 반환합니다. 활성화함수는 다양한 종류가 있으며 그 중 일반적으로 사용하는 몇 가지를 살펴보면 다음과 같습니다. 시그모이드함수(Sigmoid function) 시그모이드 함수는 식 1과 같으며 모든 값은 (0, 1) 구간내로 변환합니다. $$\begin{equation}\tag{1} \begin{aligned}&\text{sigmoid} ;\\ & f(x)=\frac{1}{1+\exp(-x)} \end{aligned} \end{equation}$$ 인공 뉴런은 임계값을 기준으로 활성화 여부를 결정합니다. 입력이 임계값을 초과할 때 값 1을 취하고 반대의 경우는 0을 취합니다. 딥러닝은 그라디언트 기반 학습으로 임계값 단위에 대한 매끄럽고 미분 가능한 근사값의 출력이 가능하여야 합니다. 시그모이드 함수는 이러한 조건을 충족하는 함수입니다. 그러나 입력이 0에 가까울 때 시그모이드 함수는 선형 변환에 접근합니다. x=torch.arange(-10, 10, 0.001, requires_grad=True) y=torch.sigmoid(x) plt.plot(x.detach().numpy(), y.detach().numpy()) plt.xlabel("x&quo

Multi-linear regression

Multi-linear regression Linear models with one or more independent variables and one response can also be built by applying the sklean.linear_model class. The construction process and evaluation method of this model are the same as the simple linear model in the previous section. Example 1)   Let's build a regression model that estimates the close price of Google (go) using the colse values of Dow Jones (dj), nasdaq (na), S&P500 (snp), VIX (vix), and the dollar index (dol) as independent variables. The data for creating a regression model is prepared as follows: Use the FinanceDataReader package to invoke data from the target event. Combine closing data from all stocks into one object. Manage missing values such as inf, Na, etc. in the data. Apply numpy.where() function, DataFrame.replace() and DataFrame.dropna() methods. The independent variables relocate to a structure that is one day ahead of the response. The last row of independent variables

Evaluation of regression coefficients, model & Estimation

Contents Evaluation of regression coefficients Evaluation of the model Regression Estimation Evaluation of regression coefficients T tests in regression analysis tests for the following null hypothesis (H0) for the regression coefficients of the generated model: H0: No significant difference by coefficient These results indicate that the test statistic, t, is outside the confidence interval and that the p-value is also close to zero, which is much lower than the significance level. Therefore, the results for the above dollor index indicate that the null hypothesis cannot be adopted. This discussion can be generalized as follows: The calculated regression coefficients also form a distribution as probability variables, so you can conduct a test. As mentioned above, the distribution has the same shape as the distribution of errors, so you can calculate the variance of the regression coefficient based on the variance of the error. As shown in Equation 1, the regression

Autocorrelation & Mean of Square Error

Contents Autocorrelation analysis Mean of Square Error Residual(Error) The generated regression model needs to be statistically tested, and the main object in the test is an error, the difference between the observations and estimates calculated by Equation 1. $$\begin{align}\tag{1}\text{e}&=y-(b_0+b_1x)\\&=y-\hat{y} \end{align}$$ Errors in the regression model have the following prerequisites: Probability variables that follow a normal distribution Because independent variables are probabilities that follow a normal distribution, the error between the response and the estimate is also a probability variable that follows a normal distribution. This means that the error cannot be artificially adjusted. Homoscedastic of error terms Various regression models are possible, as shown in Figure 1. This means that you can configure the probability distribution for the regression coefficients. This distribution has means and variances. The mean of this distrib

Regression Analysis: simple regression & regression coefficient

Contents What is Regression? Simple regression Regression Coefficient What is Regression? Regression is a statistical method of setting up a model for the relationship between variables and estimating new values through that model. Figure 1 is a graph of the force (y) corresponding to a constant height (x), showing the exact direct proportional relationship in which y increases as x increases. This relationship is based on data from generalized laws of physics, which can fully predict the forces applied at a certain height within the Earth where gravity acts. plt.figure(figsize=(7,5)) h=range(7) w=40 F=[w*9.8*i for i in h] plt.plot(h, F, "o-") plt.xlabel("Height(m)", size=13, weight="bold") plt.ylabel("Force(N)", size=13, weight="bold") plt.text(2.5, 1500, 'F=Wgh', color="blue", size=13, weight="bold") plt.text(2, -600, r'w:weight (kg), g: Gravity Acceleration($m/sec^2$)', color="