반응형
반응형

[여행] CCTV로 보는 지금 제주도 상황

이제 눈은 다 그친듯. 

http://www.jejuits.go.kr/jido/mainView.do?DEVICE_KIND=CCTV 

 

페이지 로딩중 - 제주특별자치도 교통정보센터

064-728-3248 제주시 고마로 19길 5 (일도2동 409-11) 실시간 주차 가능 대수 일반 : 15 경차 : 1 대형 : 0 긴급 : 0 장애 : 1 여성 : 0 기타 : 0 운영정보 주차면수 : 125 평일운영 : 12:00 ~ 21:00 휴일운영 : 12:00 ~ 21

www.jejuits.go.kr

반응형
반응형

[python] Python 3.11: 진정으로 즐길 수 있는 새로운 기능

https://towardsdatascience.com/python-3-11-new-features-that-you-will-truly-enjoy-9fd67882fdf

 

Python 3.11 New Features That You Will Truly Enjoy

Kudos to all the effort by volunteers across the world

towardsdatascience.com

이미지 출처: Unsplash

Python 3.11은 2022년 10월 24일에 출시되어 우리가 만져볼 수 있는 몇 가지 흥미로운 개선 사항을 제공했습니다. 여기에서 모든 PEP 의 전체 문서를 볼 수 있습니다 . 이 기사에서는 5가지와 추가로 여러분이 높이 평가할 멋진 새 기능을 제공할 것입니다.

PEP 657 : 오류 추적 로케이터

Python 3.11 이전에는 예외가 발생했을 때 오류 추적의 유일한 정보는 오류가 무엇인지 설명 하는 줄 이었습니다. 예를 들어,

x, y, z = 1 , 2 , 0
 a, b, c = 3 , 4 , 5
 결과 = (x / y / z) * (a / b / c)

이 코드는 0과 같은 나누기 때문에 오류를 발생시킵니다. X/Y by Z다음은 이치에 맞는 오류 메시지이지만 코드의 어느 부분이 이 문제를 일으켰는지 아직 모르기 때문에 정보가 아닙니다.

Python 3.11에서 우리는 이것을 보게 될 것입니다.

오류 탐지기의 도움으로 근본 원인이 Y 또는 Z가 0~~^~~ 이라는 것이 분명합니다 . 이 주석이 달린 트레이스백은 코드가 복잡해지면 더욱 강력해집니다.

PEP 673 : 자아 유형

유형 힌트의 경우 이전에는 현재 클래스 자체를 참조해야 하는 경우 아래와 같이 유형 변수 를 명시적으로 정의해야 했습니다.

이제 3.11에서는 Self 캡슐화 클래스 자체를 참조하는 유형을 사용할 수 있습니다. 이렇게 하면 유형 변수를 정의하는 번거로움이 사라집니다.

향상된 {asyncio} : 비동기 컨텍스트 관리자

비동기 프로그래밍을 사용하면 코드는 여전히 한 번에 한 단계씩 실행되지만 시스템은 다음 단계로 이동하기 전에 이 단계가 완료될 때까지 기다리지 않습니다.

파이썬에서 이것은 {asyncio}모듈에 의해 처리됩니다. 우리는 여러 비동기 작업을 생성하고 각 작업이 실행될 때까지 기다린 다음 asyncio.gather(). 예를 들어 심부름을 해보자.

 

터미널에서 실행하면 다음과 같은 결과가 나타납니다.

그러나 list 작업을 기다리기 전에 수동으로 모니터링하는 asyncio.gather것은 번거롭습니다. 새로운 기능/클래스 TaskGroup()가 3.11에 도입되었습니다.

 

TaskGroup종료 시 모든 작업을 기다리는 작업 그룹을 보유하는 컨텍스트 관리자로 기능합니다 . 또한 구문이 더 간단합니다.

PEP 654 : 예외 그룹

예외 처리를 위한 유사한 "그룹화" 기능은 3.11에 추가된 예외 그룹 입니다. 단일 예외에 래핑된 여러 일반 예외로 생각할 수 있습니다.

볼 수 있듯이 오류가 를 트리거하면 ExceptionGroup자체 패널에 표시된 두 하위 예외가 모두 발생했습니다.

처리 하기 위해 ExceptionGroup Python 3.11에는 새 키워드도 추가되었습니다 except*.

를 사용하면 except*에 래핑된 여러 오류 ExceptionGroup 가 처리됩니다. 이 기능은 여러 비동기 작업이 함께 실행되는 { asyncio } 에서 사용될 때 더 효과적입니다.

PEP 678 : 사용자 지정 예외 사항

add_note오류 처리를 위한 또 다른 훌륭한 새 기능은 사용자 지정 메시지를 추가할 수 있는 예외 메모입니다 . 예를 들어,

보너스 PEP 659 : 더 빠른 실행 속도

존경하는 가작으로 Python 3.11은 Faster CPython 이니셔티브 덕분에 이전 버전보다 10%-60% 더 빠를 것으로 예상됩니다.

결론: Python 3.11로 업그레이드해야 합니까?

때에 따라 다르지! 개인적으로 프로젝트에 사용된 특정 라이브러리가 아직 Python 3.11과 호환되지 않을 수 있으므로 프로덕션 환경을 업그레이드하지 않도록 주의 해야 합니다.

테스트해보고 싶다면 Google colab에서 테스트하는 것이 좋습니다. 다음을 실행하여 Python 버전을 3.11로 업그레이드할 수 있습니다.

!sudo apt-get 업데이트 -y 
!sudo apt-get install python3 .11
 !sudo 업데이트 대안 --install /usr/ bin /python3 python3 /usr/ bin /python3 .7  1
 !sudo 업데이트 대안 --install / usr/ bin /python3 python3 /usr/ bin /python3 .11  2

이 기사에서는 가장 흥미로운 새 기능만 살펴보았습니다. 모든 개선 사항 및 변경 사항에 대한 공식 릴리스 문서 를 확인하십시오 .

반응형
반응형

데이터 과학자를 위한 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!

반응형
반응형

새로운 아이디어는 어디에서 나오는가? 답은 간단하다. 바로 다름이다.
다양한 창의력 이론이 존재하지만, 이들 모두가 공유하는 유일한 교리는
‘전혀 상관없어 보이는 것을 나란히 놓는 구조에서 창의성이 나온다’는 것이다.
다름을 최대화하는 최적의 방식은 연령과 문화, 학문을 섞는 것이다.
- 니콜라스 네그로폰테, MIT 미디어랩 소장


다름을 인정하는 데서 창조가 시작됩니다.
다양성은 발전을 자극하고, 동질성은 발전을 늦춥니다.
다른 시각을 가지고 여러 가지 다른 이론들을 이리저리 배열해보면
새로운 아이디어가 떠오르기 마련입니다.

반응형
반응형

그러므로 쉰다는 것은
외부의 강제성을 벗어난 상태,
스스로를 지킬 수 있는 자기존엄성과 연결된다.
자기존엄성이란 자율적으로 결정할 수 있는 상태,
즉 '자기결정권'이 보장된 상태에서 가능하다. 이
자기결정권은 그저 단순한 의지의 표현이 아니라,
자기한테 필요한 자원에 접근할 수 있고
그 자원을 사용할 수 있는 권리를
포함한다.  


- 이승원의《우리는 왜 쉬지 못하는가》중에서 -


* 쉼은 '내어맡김'입니다.
'애씀'을 내려놓고, 내어맡길 때
진정한 쉼이 찾아옵니다. 그래서 욕조에서
긴장을 풀고 있을 때나, 단잠에서 깨어날 무렵에
섬광 같은 직감이 다가오기도 합니다. 아르키메데스의
'유레카'의 외침도 그렇게 생긴 것입니다.
쉼이 가져다주는 선물입니다.

반응형

'아침편지' 카테고리의 다른 글

보물 상자를 깔고 앉은 걸인  (0) 2023.01.27
진통제를 먹기 전에  (0) 2023.01.26
한마음, 한느낌  (0) 2023.01.24
편안한 쉼이 필요한 이유  (0) 2023.01.20
회의 시간은 1시간 안에  (0) 2023.01.19
반응형

공감은
보이지 않는 고비들을
계속 넘어갈 수 있게 해주는 힘이다.
그에 기대어 자기 속마음으로 들어가
숨어 있던 자기를 만날 수 있다. 그에
기대어 자기의 전모에 대한 조망권도
확보할 수 있게 된다.


- 정혜신의《당신이 옳다》중에서 -


* 공감은
한마음, 한느낌이라고도 합니다.
혼자가 아닌, 함께 하고 있음을 알게 해주고,
자기 자신을 그대로 품어 안아줄 수 있는 치유의 힘을
선물해 줍니다. 보이지 않는 마음의 징검다리를
건널 수 있게 곁에 있어주는 당신이 있어
오늘도 힘차게 발걸음을 내디뎌 봅니다. 

반응형

'아침편지' 카테고리의 다른 글

진통제를 먹기 전에  (0) 2023.01.26
쉼이 가져다주는 선물  (0) 2023.01.25
편안한 쉼이 필요한 이유  (0) 2023.01.20
회의 시간은 1시간 안에  (0) 2023.01.19
뿌리 깊은 사랑  (0) 2023.01.18

+ Recent posts