Programming

Scikit의 임의 상태 (의사 난수)“malloc_error_break에서 중단 점을 설정하여 디버깅하는 방법”

procodes 2020. 7. 27. 08:01
반응형

Scikit의 임의 상태 (의사 난수)


scikit learn에서 기계 학습 알고리즘을 구현하고 싶지만이 매개 변수의 기능을 이해하지 못 random_state합니까? 왜 사용해야합니까?

또한 의사 난수 (Pseudo-random) 숫자가 무엇인지 이해할 수 없었습니다.


train_test_split배열 또는 행렬을 임의의 기차 및 테스트 하위 집합으로 나눕니다. random_state,를 지정하지 않고 실행할 때마다 다른 결과가 표시됩니다. 이는 예상 된 동작입니다. 예를 들면 다음과 같습니다.

실행 1 :

>>> a, b = np.arange(10).reshape((5, 2)), range(5)
>>> train_test_split(a, b)
[array([[6, 7],
        [8, 9],
        [4, 5]]),
 array([[2, 3],
        [0, 1]]), [3, 4, 2], [1, 0]]

달리기 2

>>> train_test_split(a, b)
[array([[8, 9],
        [4, 5],
        [0, 1]]),
 array([[6, 7],
        [2, 3]]), [4, 2, 0], [3, 1]]

바뀐다. 반면에을 사용 random_state=some_number하면 Run 1 의 출력이 Run 2 의 출력과 같을 것입니다 . 즉, 스플릿은 항상 동일합니다. 실제 random_state숫자가 42, 0, 21 등은 중요 하지 않습니다 . 중요한 것은 42를 사용할 때마다 처음 분할 할 때 항상 동일한 출력을 얻는다는 것입니다. 이것은 예를 들어 문서에서 재현 가능한 결과를 원할 때 유용하므로 예제를 실행할 때 모든 사람이 동일한 숫자를 일관되게 볼 수 있습니다. 실제로 나는 말할 것입니다. random_state물건을 테스트하는 동안 고정 숫자로 설정해야 하지만 실제로 무작위 (고정되지 않은) 스플릿이 필요한 경우 프로덕션에서 제거해야합니다.

두 번째 질문과 관련하여 의사 난수 생성기는 거의 임의의 숫자를 생성하는 숫자 생성기입니다. 그들이 무작위로 무작위가 아닌 이유는이 질문의 범위를 벗어 났으며 아마도 귀하의 경우에는 중요하지 않을 것입니다 . 자세한 내용 여기를 살펴보십시오 .


random_state코드에서를 지정하지 않으면 코드를 실행할 때마다 새로운 임의의 값이 생성되고 열차 및 테스트 데이터 세트는 매번 다른 값을 갖습니다.

그러나 고정 값이 할당 된 경우 random_state = 42코드를 몇 번이나 실행하더라도 결과는 동일합니다 (즉, 열차 및 테스트 데이터 세트에서 동일한 값).


코드에서 random_state를 언급하지 않으면 코드를 실행할 때마다 새로운 임의의 값이 생성되고 열차 및 테스트 데이터 세트는 매번 다른 값을 갖습니다.

그러나 random_state (random_state = 1 또는 다른 값)에 특정 값을 사용할 때마다 결과는 동일합니다 (즉, 기차 및 테스트 데이터 세트의 동일한 값). 아래 코드를 참조하십시오 :

import pandas as pd 
from sklearn.model_selection import train_test_split
test_series = pd.Series(range(100))
size30split = train_test_split(test_series,random_state = 1,test_size = .3)
size25split = train_test_split(test_series,random_state = 1,test_size = .25)
common = [element for element in size25split[0] if element in size30split[0]]
print(len(common))

코드를 몇 번이나 실행하든 상관없이 출력은 70입니다.

70

random_state를 제거하고 코드를 실행하십시오.

import pandas as pd 
from sklearn.model_selection import train_test_split
test_series = pd.Series(range(100))
size30split = train_test_split(test_series,test_size = .3)
size25split = train_test_split(test_series,test_size = .25)
common = [element for element in size25split[0] if element in size30split[0]]
print(len(common))

이제 코드를 실행할 때마다 출력이 달라집니다.


random_state number는 테스트 및 학습 데이터 세트를 임의의 방식으로 분할합니다. 여기에 설명 된 것 외에도 random_state 값이 모델의 품질에 상당한 영향을 미칠 수 있음을 기억하는 것이 중요합니다 (품질에 따라 본질적으로 예측 정확도를 의미 함). 예를 들어 random_state 값을 지정하지 않고 특정 데이터 집합을 가져와 회귀 모델을 학습하면 매번 테스트 데이터에서 학습 된 모델에 대해 다른 정확도 결과를 얻을 수 있습니다. 따라서 가장 정확한 모델을 제공 할 수있는 최상의 random_state 값을 찾는 것이 중요합니다. 그런 다음이 숫자는 다른 연구 실험과 같은 다른 경우에 모델을 재현하는 데 사용됩니다. 그렇게하려면

for j in range(1000):

            X_train, X_test, y_train, y_test = train_test_split(X, y , random_state =j,     test_size=0.35)
            lr = LarsCV().fit(X_train, y_train)

            tr_score.append(lr.score(X_train, y_train))
            ts_score.append(lr.score(X_test, y_test))

        J = ts_score.index(np.max(ts_score))

        X_train, X_test, y_train, y_test = train_test_split(X, y , random_state =J, test_size=0.35)
        M = LarsCV().fit(X_train, y_train)
        y_pred = M.predict(X_test)`


If there is no randomstate provided the system will use a randomstate that is generated internally. So, when you run the program multiple times you might see different train/test data points and the behavior will be unpredictable. In case, you have an issue with your model you will not be able to recreate it as you do not know the random number that was generated when you ran the program.

If you see the Tree Classifiers - either DT or RF, they try to build a try using an optimal plan. Though most of the times this plan might be the same there could be instances where the tree might be different and so the predictions. When you try to debug your model you may not be able to recreate the same instance for which a Tree was built. So, to avoid all this hassle we use a random_state while building a DecisionTreeClassifier or RandomForestClassifier.

PS: You can go a bit in depth on how the Tree is built in DecisionTree to understand this better.

randomstate is basically used for reproducing your problem the same every time it is run. If you do not use a randomstate in traintestsplit, every time you make the split you might get a different set of train and test data points and will not help you in debugging in case you get an issue.

From Doc:

If int, randomstate is the seed used by the random number generator; If RandomState instance, randomstate is the random number generator; If None, the random number generator is the RandomState instance used by np.random.


sklearn.model_selection.train_test_split(*arrays, **options)[source]

Split arrays or matrices into random train and test subsets

Parameters: ... 
    random_state : int, RandomState instance or None, optional (default=None)

If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. source: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html

'''Regarding the random state, it is used in many randomized algorithms in sklearn to determine the random seed passed to the pseudo-random number generator. Therefore, it does not govern any aspect of the algorithm's behavior. As a consequence, random state values which performed well in the validation set do not correspond to those which would perform well in a new, unseen test set. Indeed, depending on the algorithm, you might see completely different results by just changing the ordering of training samples.''' source: https://stats.stackexchange.com/questions/263999/is-random-state-a-parameter-to-tune

참고URL : https://stackoverflow.com/questions/28064634/random-state-pseudo-random-number-in-scikit-learn

“malloc_error_break에서 중단 점을 설정하여 디버깅하는 방법”


내 응용 프로그램 충돌없이 이와 같은 많은 콘솔 출력이 나타납니다.

malloc : * 객체 0xc6a3970에 대한 오류 : 포인터가 해제되지 않았습니다. * malloc_error_break에서 중단 점을 설정하여 디버그하십시오.

어떤 객체 또는 변수가 영향을 받는지 어떻게 알 수 있습니까?

다음과 같은 상징적 중단 점을 설정하려고 시도했지만 멈추지 않습니다.

여기에 이미지 설명을 입력하십시오


중단 점 탐색기 (보기-> 네비게이터-> 중단 점 탐색기 표시 또는 ⌘7)를 열고 왼쪽 아래 모서리에있는 더하기 단추를 클릭하고 "기호 중단 점 추가"를 선택하여 malloc_error_break ()에 중단 점을 설정하십시오. 팝업이 malloc_error_break나타나면 Symbol 필드에 입력 한 다음 Done을 ​​클릭하십시오.

편집 : openfrog는 스크린 샷을 추가하고 내 답변을 게시 한 후 이미 성공하지 않고 이러한 단계를 시도했다고 나타냅니다 . 그 편집으로, 나는 무엇을 말할지 잘 모르겠습니다. 나는 그것이 스스로 작동하지 않는 것을 보지 못했고 실제로 malloc_error_break 세트에서 항상 중단 점을 유지합니다.


스크린 샷에서 모듈을 지정하지 않았습니다. "libsystem_c.dylib"설정을 시도하십시오.

여기에 이미지 설명을 입력하십시오

나는 그것을했고 그것을 작동 : 중단 점은 여기서 멈 춥니 다 (그러나 스택 트레이스는 종종 모호한 시스템 라이브러리에서 발생하지만 ...)


Xcode와 동일한 문제가있었습니다. 나는 당신이 준 단계를 수행했지만 작동하지 않았습니다. 내가 본 모든 포럼 에서이 문제에 대한 모든 단서가 당신이 준 것이기 때문에 미쳤습니다. 나는 malloc_error_break 뒤에 공백을 넣은 것을 보았습니다. 억제하고 이제는 작동합니다. 벙어리 문제이지만 솔루션이 작동하지 않으면 malloc_error_break 전후에 공간을 두지 마십시오.

이 메시지가 도움이 되길 바랍니다 ..


일부 폴더 (특히 / usr / bin /)에 쓸 필요가없는 권한을 부여하여 문제를 일으켰습니다. 디스크 유틸리티를 열고 Macintosh HD 디스크에서 '디스크 복구 권한'을 실행하여 문제를 해결했습니다.


가까운 사파리 인스펙터로 해결합니다. 게시물을 참조하십시오 . 테스트를 위해 앱을 실행할 때 가끔 소리가 나고 자동 검사기를 켜고 사파리를 연 다음 앱에서 몇 가지 작업을 수행 한 다음이 문제가 발생했습니다.

여기에 이미지 설명을 입력하십시오

참고 URL : https://stackoverflow.com/questions/14045208/how-to-set-a-breakpoint-in-malloc-error-break-to-debug

반응형