반응형

데이터 과학자를 위한 6가지 Python 팁

https://towardsdatascience.com/top-6-python-tips-for-data-scientists-4f4a25e44d15

 

Top 6 Python Tips for Data Scientists

Practical tips and tricks from my daily analytics projects

towardsdatascience.com

 

 

### 데이터 과학자를 위한 6가지 Python 팁
### Top 6 Python Tips for Data Scientists
### https://towardsdatascience.com/top-6-python-tips-for-data-scientists-4f4a25e44d15

codeString = '''a,b = 4,5; print(f"a = {a} and b = {b}"); print(f"a+b = {a+b}")'''
exec(codeString)

print("\n\n\n")


import os
import sys

#작업하는 경로(위치)가 어디인지 확인
print(os.getcwd())


exec(open("./Project/Datascientist/myFullFileName.py").read())

print("\n\n\n")

### 각각 현재 작업 디렉토리 또는 사용자 지정 디렉토리의 모든 파일을 나열합니다.
print( os.listdir() )



"""_summary_
"""
print("\n\n\n")

### 4. Code timer as a decorator 
import time
import requests

def timerWrapper(func):
    """Code the timer"""

    def timer(*args, **kwargs):
        """Start timer"""
        start = time.perf_counter()
        
        output = func(*args, **kwargs)
        
        timeElapsed = time.perf_counter() - start
        print(f"Current function: {func.__name__}\n Run Time: {timeElapsed}")
        return output

    return timer

## Func to make a request to an user-defined url
@timerWrapper
def getArtile(url):
    return requests.get(url, allow_redirects=True)

## Monitor the runTime 
if __name__ == "__main__":
    getArtile('https://towardsdatascience.com/6-sql-tricks-every-data-scientist-should-know-f84be499aea5')
    

print("\n\n\n")
    
## 이제 다른 함수의 시간을 측정 @timeWrapper하려면 함수 앞에 the를 놓는 것뿐입니다.
@timerWrapper
def getMultiplication(num):
    for val in range(num):
        print(10**(10**val))

getMultiplication(3)

Now, let’s jump right in!

  1. Dynamic execution with exec()

Dynamic Execution (Image Source)

Scenario: You inherited a Python project from a colleague, and immediately noticed that those scripts all have a whopping 5000+ lines of code. The same chunks (of code) got copied and pasted multiple times! So, is there a more efficient option to go about code reusability?

Let’s explore the exec() function in Python. Simply put, it takes in a string or object code, and execute it as shown in this example,

 
a = 4 and b = 5
a+b = 9

Even more handy? We can use exec(open().read()) to call and execute a file within the Python interpreter. For example,

 

With this powerful one-liner, data scientists can save programs that will be reused as standalone files, and execute them whenever needed within the main program. No code copying and pasting any more!

Being a cool functionality in Python, exec() has one pitfall to avoid — it does NOT return any value,

 
a = 4 and b = 5
a+b = 9
** Is the return from exec() is None? True **

As we can see, the output of the exec() function is None; hence, it cannot be used to store any values, which is equivalent to the sounce()function in R.

***Join our YouTube community 🎦 “Data Talks with Kat” 😄

 

2. Operating system commands with {os} and {shutil}

Scenario: continue from our previous tip, now you want to check out the script before executing it. Don’t bother to double-click your mouse all the way through to open up the file? No problem, you can easily achieve this in Python directly without interrupting your train of thought.

 

Here, the os.startfile() function allows users to open up any type of files, including MS documents, Excels, R and SQL scripts.

Similarly, we can also delete a FILE using os.remove(“myFullFileName.ANYFORMAT”)

or delete the entire DIRECTORY using shutil.rmtree(“folderToBeRemoved”). where {shutil} is a Python module that offers a number of high-level file operations, particularly for file copying and removal.

Therefore, if you haven’t used {os} other than os.getcwd() or os.chdir() or if the {shutil} sounds unfamiliar, it’s time to check out their documents. You will definitely find useful commands or file system methods that make your coding easier. Here lists a few of my favorites,

  • os.listdir() or os.listdir(“someDirectory”) — list all files in the currently working directory or any user-specified directory, respectively;
  • os.path.join() — automatically create a path with elements in the arguments for later use, e.g., os.path.join(‘D’, ‘Medium’, ‘New Folder’) will return
 ‘D\\Medium\\New Folder’
  • os.makedirs() — create a directory;
  • shutil.copy2(“sourcePath”, “destinationPath”) or shutil.move(“sourcePath”, “destinationPath”) — copy or cut a file respectively.

3. One-liner: Nested list comprehension to get rid of the for loops

Scenario: this “simple” task we come across is to combine several lists into one big long list,

 

Surely, we can write five nested for loops to append each sublist to the final output list. But it’s smarter to turn to nested list comprehension for the most concise way,

 

4. Timer wrapped as a decorator

Timer as a decorator (Image Source)

Scenario: while Python is recognized as one of the most effective programming languages, data scientists still need to check the runtime of our programs.

It’s not the hardest thing if we just implement a bare-bones Python timer for each function we want to monitor. However, if we code it as a decorator, we would make our timer much easier to be version-controlled and reused!

Here is how,

 

In this snippet,

  • the timer is wrapped in a timerWrapper function, which then is used as a decorator called prior to the main function;
  • The example main function is to return a request connecting to an URL, which is one of my previous blogs.

Running this code gives us the time elapsed,

Current function: getArtile
 Run Time: 1.6542516000008618Out[101]: <Response [200]>

Now, to time another function, all we need is to put the @timeWrapper in front of the function,

 
getMultiplication(3)
10
10000000000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Current function: getMultiplication
 Run Time: 0.00014700000065204222

5. Leverage the options system to customize your display

Scenario: as data scientists, we analyze data with {pandas} and {numpy} on a daily basis. When I first learned coding in Python, I was frustrated seeing this after reading my data into the IDE,

Clearly, data display is cut off both row-wise and column-wise, and the following code can fix it,

 

Here, we are explicitly setting the maximum columns, rows and column width to display/print in the console. There are numerous customizable options and settings in {pandas}, and similar operations are also available in {numpy} for arrays and matrix,

 

6. Reproduce your machine learning model results? Set seeds!

Scenario: Due to the stochastic nature of machine learning modeling process, we have all encountered the non-deterministic aspect of machine learning. This randomness results in our difficulty reproducing the same results across different runs. Consequently, it’s challenging to figure out whether an improvement in performance metrics is a result of successful model tuning or simply a different random training/testing sample.

Luckily the reproducibility can be achieved by setting the random seed throughout your model pipeline, provided that you do it correctly! How many times have you seen questions like “Getting a different result despite random seed defined” popping up on Stack Overflow? Well, how to appropriately set seeds should be in the first page of documentations, but it took me some time to dig it out.

I found that NOT every seed is defined the same in {numpy}, {sklearn}, {tensorflow} or {torch}. Thus, it’s a best practice to use a definitive function that sets all SEEDS for all your frameworks. For example,

 

Adding this tactical reset_random_seed() function to all necessary steps of your workflow, such as train-test split, model compile/training, and interpretation, will get you half way to full reproducibility. More detailed visibility into your experiments will finish the second half!

반응형
반응형

https://www.itworld.co.kr/news/242939?page=0,1 

 

"이러려고 데이터 과학자 됐나" 데이터 관리의 11가지 어두운 비밀 - ITWorld Korea

누군가는 데이터를 새로운 석유라 부르고, 누군가는 새로운 금이라고도 부른다. 철학자와 경제학자들은 비유의 적절성 대해 논쟁할 수 있겠지만, 데이터 기반 의사 결정을 도모하는 기업에 데

www.itworld.co.kr

"이러려고 데이터 과학자 됐나" 데이터 관리의 11가지 어두운 비밀

누군가는 데이터를 새로운 석유라 부르고, 누군가는 새로운 금이라고도 부른다. 철학자와 경제학자들은 비유의 적절성 대해 논쟁할 수 있겠지만, 데이터 기반 의사 결정을 도모하는 기업에 데이터 구성 및 분석이 필수적이라는 점은 의심의 여지가 없다.

일단은 견고한 데이터 관리 전략이 핵심이다. 데이터 거버넌스, 데이터 운영, 데이터 웨어하우징, 데이터 엔지니어링, 데이터 분석, 데이터 과학 등을 포괄하는 데이터 관리는 올바르게 수행될 경우 각종 비즈니스에서 경쟁 우위를 가져다줄 수 있다.

좋은 소식은 데이터 관리의 많은 측면이 잘 정립돼 있으며, 수십 년 동안 발전해 온 원칙이 존재한다는 점이다. 예를 들어, 적용하기 어렵거나 이해하기에 간단하지 않을 수 있지만, 많은 과학자와 수학자 덕분에 기업은 이제 데이터를 분석하고 결론을 내리기 위한 다양한 프레임워크를 갖게 됐다. 분석 한계를 나타내는 오차 막대를 그리는 통계 모델도 있다.

그러나 데이터 과학과 이를 뒷받침하는 다양한 학문에 대한 연구에서 얻은 모든 장점에도 불구하고 우리는 머리를 긁적거릴 때가 있다. 현장에서 벽에 부딪히는 경우가 많기 때문이다. 때로는 너무 많은 데이터를 수집하고 구성하는 역설적인 문제도 있다. 일부는 철학적이며 우리의 추상적 역량을 시험한다. 그리고 처음 데이터를 수집하는 데서는 개인 정보 보호 문제가 대두되고 있다.

다음은 수많은 기업에서 데이터 관리를 어려운 과제로 만드는 몇 가지 어두운 비밀들이다.


애물단지 비정형 데이터
기업 아카이브에 저장되어 있는 데이터의 대부분은 구조화되어 있지 않다. 은행의 콜센터 직원이 작성한 문자 메모를 검색하기 위한 인공 지능(AI) 사용을 원하는 경우가 있다. 이 문장에는 은행의 대출 및 서비스를 개선하는 데 도움이 될 수 있는 통찰이 담겨 있을 수 있다. 그러나 메모 데이터는 기록할 내용에 관해 서로 다른 생각을 가진 수백 명의 사람들이 작성한 것이다. 또한, 직원들은 서로 다른 작문 스타일과 능력을 가지고 있고, 일부는 전혀 쓰지 않았다. 또 어떤 사람들은 주어진 전화에 대해 너무 많은 정보를 기록한다. 수십 년 동안 수백 명의 직원이 작성한 텍스트 더미가 있다면, 구조화 수준이 훨씬 더 약해질 수 있다.

정형 데이터라도 비정형인 경우
좋은 데이터 과학자와 데이터베이스 관리자는 각 분야의 유형과 구조를 명료하게 지정해 데이터베이스를 마련한다. 때로는 필드의 값을 특정 범위의 정수 또는 미리 정의된 선택으로 제한한다. 하지만 사람들은 데이터베이스가 주름과 결함을 추가하는 방법을 생각해낸다.

필드가 비어 있는 경우도 있다. 질문이 적용되지 않는다고 생각할 때 ‘n.a.’를 넣기도 하지만, 그저 대시 기호를 넣는 이들도 있다. 사람들은 심지어 이름을 해마다, 날마다 다르게 표시하기도 한다. 

우수한 개발자는 유효성 검사를 통해 이런 문제 중 일부를 파악한다. 훌륭한 데이터 과학자는 정리를 통해 이런 불확실성을 어느 정도 줄일 수도 있다. 그러나 탁월하게 구조화된 표에도 의심스러운 항목이 있고, 이런 의심스러운 항목에 알 수 없는 항목과 분석 오류가 발생할 수 있다. 좌절감을 느끼게 하는 현실이다.

너무 엄격하거나 느슨한 데이터 스키마
데이터팀이 스키마 제약 조건을 아무리 자세히 설명하려 해도 다양한 데이터 필드의 값을 정의하기 위한 스키마는 완벽하기 어렵다. 너무 엄격하거나 너무 느슨하다. 데이터팀에서 엄격한 제약 조건을 추가하면 사용자는 허용 가능한 값의 좁은 목록에서 답을 찾을 수 없다고 불평한다. 스키마가 너무 수용적이면 사용자는 일관성이 거의 없이 이상한 값을 추가할 수 있다. 스키마를 올바르게 조정하는 것은 거의 불가능할 지경이다.

매우 엄격한 데이터 법률
개인정보 보호 및 데이터 보호에 관한 법률은 이미 강력하며, 점점 더 강력해지고 있다. GDPR, HIPPA 및 각종 규제 사이에서 데이터를 수집하는 것은 매우 어려울 수 있으며, 해커의 침입에 대응하기란 훨씬 더 위험할 수 있다. 많은 경우에 프로그래머나 데이터 과학자보다 변호사에게 비용을 지출하는 것이 더 쉬울 수 있다. 이런 골칫거리로 인해 일부 기업은 데이터를 제거할 수 있는 즉시 데이터를 폐기한다.

엄청난 데이터 정리 비용
많은 데이터 과학자가 자신의 작업 중 90%가 데이터를 수집하고, 일관된 형식으로 만들고, 끝없는 구멍이나 실수를 처리하는 것이라고 본다. 데이터를 가지고 있는 사람은 항상 “CSV에 모든 것이 있다”라고 말할 것이다. 그러나 그들은 빈 필드나 잘못된 특성을 언급하지 않는다. 실제로 통계 분석을 수행하기 위해 R 또는 파이썬에서 루틴을 시작하는 것보다 데이터 과학 프로젝트에서 사용할 데이터를 정리하는 데 10배나 더 많은 시간을 소비하기 쉽다.

사용자의 의심 증가
최종 사용자와 고객이 기업의 데이터 관리 관행에 대해 점점 더 의심을 품고 있다. 일부 AI 알고리즘에 대한 불안감과 두려움이 증폭되고 있다. 일거수일투족을 감시하는 듯한 반응을 보이기도 한다. 이런 두려움은 규제를 조장하고 종종 기업과 선의의 데이터 과학자를 괴롭힌다. 사용자가 의도적으로 가짜 값이나 오답으로 데이터 수집을 방해하는 경향을 보이는 것이다. 때로는 작업의 절반이 악의적인 파트너 및 고객을 상대하는 업무가 될 수 있다.

 

외부 데이터와의 통합 위험성
공격적인 기업은 자사의 정보를 서드파티 데이터 및 인터넷에 떠도는 방대한 개인화된 정보와 통합하는 방법을 모색하고 있다. 실제로 일부 도구는 모든 고객에 대한 데이터를 흡수해 각 구매에 대해 개인화된 정보를 작성하겠다고 공개적으로 공언한다. 그렇다, 이들은 사용자의 패스트푸드 구매와 신용 점수를 추적하는 데 첩보기관이 테러리스트를 추적하는 데 사용하는 기술을 사용한다. 사람들이 불안해하는 것이 사실 당연하다.

데이터 사용을 단속하는 규제 당국
데이터 분석이 언제 어떤 선을 넘을지 알기 어렵지만, 일단 선을 넘으면 규제 당국이 나타난다. 캐나다의 최근 사례에서, 정부는 일부 도넛 가게가 어떻게 경쟁업체에서 쇼핑하는 고객들을 추적하고 있는지 조사했다. 

정부는 보도 자료를 통해 “조사 결과, 팀 호튼스가 미국의 서드파티 위치 서비스 업체와 맺은 계약에 너무 모호하고 허용적인 표현이 포함되어 있었다. 이로 인해 회사가 ‘비식별화된’ 위치 데이터를 판매할 소지를 남겼을 것”이라고 밝혔다. 도대체 무엇을 위해? 더 많은 도넛을 팔기 위해서? 규제기관은 개인정보와 관련된 모든 것에 점점 더 주의를 기울이고 있다.

도출한 결과가 무가치함
우리는 뛰어난 알고리즘이 모든 것을 더 효율적이고 수익성 있게 만들 수 있다고 상상한다. 그리고 때로는 그런 알고리즘을 실제로 구현할 수 있다. 그러나 비용이 문제이다.

실제로 소비자는 물론 심지어 기업까지도 정교한 데이터 관리 체계에서 나오는 표적 마케팅의 가치에 점점 더 의문을 제기하고 있다. 이미 구매한 아이템에 대한 광고가 노출되는 것을 자주 경험했을 것이다. 엄격한 데이터 분석을 통해 실적이 낮은 공장을 식별했더니, 회사가 건물에 30년 임대 계약을 체결했을 수도 있다. 기업은 데이터 과학이 비현실적인 답을 산출할 가능성에 대비해야 한다.

결국 인간의 직관에 따라 결정
숫자는 높은 정확도를 제공하지만, 사람이 숫자를 어떻게 해석하는지가 더 중요한 경우도 많다. 모든 데이터 분석과 AI 마법이 끝난 후에 대부분 알고리즘은 일부 값이 임계 값을 초과하는지 또는 미만 인지에 대한 결정을 내려야 한다. 

가령 경찰은 제한 속도의 20%를 초과하는 차량에 속도위반 고지서를 주려고 한다. 이런 임계값은 종종 임의의 값이다. 데이터에 적용할 수 있는 모든 과학 및 수학의 경우, ‘데이터 기반’ 프로세스에는 생각보다 더 많은 회색 지대가 있다. 기업이 데이터 관리 프랙티스에 투입한 방대한 자원에도 불구하고 결국 의사 결정에 영향을 미치는 최대 요인은 인간의 직관인 경우가 많다.

폭발적인 데이터 스토리지 비용
테라바이트당 가격은 계속 떨어지고 있지만 프로그래머는 더 빠르게 데이터 비트를 모으고 있다. 사물 인터넷 디바이스는 계속해서 데이터를 업로드하고, 사용자는 이런 바이트의 풍부한 컬렉션을 영원히 탐색할 것으로 기대한다.  동시에 컴플라이언스 담당자와 규제기관은 감사를 위해 계속해서 더 많은 데이터를 요구한다. 실제로 다시 액세스되는 데이터의 비율은 계속 낮아지고 있다. 그저 데이터가 하염없이 쌓여만 가는 것이다. 

반응형

+ Recent posts