로봇-AI

[파이썬7강] Working with External Libraries

happynaraepapa 2025. 1. 6. 15:45

sources :
https://www.kaggle.com/code/colinmorris/working-with-external-libraries

Working with External Libraries

Explore and run machine learning code with Kaggle Notebooks | Using data from No attached data sources

www.kaggle.com


In this tutorial, you will learn about imports in Python, get some tips for working with unfamiliar libraries (and the objects they return), and dig into operator overloading.
외부 라이브러리를 이용하는 방법에 대해서 살펴보고, 연산자(operator) 오버로딩(overloading)에 대해서 알아보자.

Imports

So far we've talked about types and functions which are built-in to the language.
여태까지는 파이썬에 #내장된 데이터타입과 함수에 대해서 이야기했다.
#내장된 built-in의 의미는 기본적인 파이썬 패키지를 깔았을 때 같이 들어 있다는 의미 정도로 이해.

But one of the best things about Python (especially if you're a data scientist) is the vast number of high-quality custom libraries that have been written for it.
파이썬이 좋은 점 중 하나는 아주 높은 수준의 외부 라이브러리가 존재하고 이를 쉽게 이용할 수 있다는 점이다.

Some of these libraries are in the "standard library", meaning you can find them anywhere you run Python. Other libraries can be easily added, even if they aren't always shipped with Python.
라이브러리중 일부는 standard library로 어디서 파이썬을 돌려도 찾을 수 있는 표준 라이브러리이고, 나머지는 파이썬과 같이 동봉되어 배포되지는 않지만, 쉽게 더해서 사용할 수 있다.

Either way, we'll access this code with imports.
우리는 이 코드를 직접 적어 넣을 수도 있고, import 를 활용하여 접근할 수도 있다.

We'll start our example by importing math from the standard library.
아래에서는 표준 라이브러리인 math를 import하는 사례를 들어 설명하고 있다.
...
#여기서 잠깐~!
라이브러리는 데이터 타입과 함수의 모음이라고 볼 수 있겠다. 라이브러리나 모듈은 유사하게 쓰이지만 라이브러리가 좀 더 넓고 크다. 함수 아래 다시 함수나 메소드가 나열되는 계층적 구조가 가능하기 때문에 import를 진행하는 방법과 결과가 다양할 것.

math is a module. A module is just a collection of variables (a namespace, if you like) defined by someone else. We can see all the names in math using the built-in function dir().
math는 모듈로, 모듈이란 단순히 변수의 모음이라고 생각할 수 있다.
모듈 내용물은 dir() 메소드로 알 수 있다.
...
We can access these variables using dot syntax. Some of them refer to simple values, like math.pi:
우리는 이 값들에 접근할 수 있을 뿐만아니라, pi(원주율 파이)값과 같은 변수를 직접 대체할 수도 있다.
...
Of course, if we don't know what math.log does, we can call help() on it:
물론, 만약 math.log가 뭔지 모르겠다면 이 메소드에 대해서 help()를 적용할 수도 있다.
...
We can also call help() on the module itself. This will give us the combined documentation for all the functions and values in the module (as well as a high-level description of the module). Click the "output" button to see the whole math help page.
또 math 모듈 자체에 help를 사용할 수도 있다.

Other import syntax
If we know we'll be using functions in math frequently we can import it under a shorter alias to save some typing (though in this case "math" is already pretty short).
만약 math에 있는 함수를 자주 써야 한다면 math를 좀 더 줄여서 사용할 수 있는 alias (앨리어스; 사투리; 방언; 줄임말)를 사용할 수 있다.
...
You may have seen code that does this with certain popular libraries like Pandas, Numpy, Tensorflow, or Matplotlib. For example, it's a common convention to import numpy as np and import pandas as pd.
Pandas, Numpy, Tensorflow, Matplotlib 등 다양한 라이브러리에서 이 방법을 고정적으로 사용하는 것을 보게 될 것이다.
예를 들어 import numpy as np 또는 import pandas as pd 이다.

The as simply renames the imported module. It's equivalent to doing something like:
이것은 단순히 import 되고 있는 모듈의 이름을 재정의한 것에 지나지 않으며 다음과 같은 의미다.
>>
import math
>>
mt = math

Wouldn't it be great if we could refer to all the variables in the math module by themselves? i.e. if we could just refer to pi instead of math.pi or mt.pi? Good news: we can do that.
math 모듈에 있는 변수 그대로를 조회(사용)할 수 있다면 정말 편하지 않을까? 예를 들어 mt.pi가 아닌 pi를 그대로 사용할 방법이 있을까? 좋은 소식은 가능하다는 것이다. 아래 예시를 보자.
...
These kinds of "star imports" can occasionally lead to weird, difficult-to-debug situations.
이런 종류의 star(*)를 활용한 import 방법은 때로는 매우 이상한, 어려운 디버깅 상황을 만들어 내기도 한다.

The problem in this case is that the math and numpy modules both have functions called log, but they have different semantics. Because we import from numpy second, its log overwrites (or "shadows") the log variable we imported from math.
이 경우 문제는 math와 numpy 모듈 모두 log라는 함수를 가지고 있지만 의미가 달라서 문제가 된 경우다.
우리가 numpy를 나중에 star import 하면 앞에서 import 한 math의 함수 log를 덧 씌우게 된다.

A good compromise is to import only the specific things we'll need from each module:
좋은 대안은 각 모듈에서 필요한 것만 선별적으로 import 하는 것이다.

Submodules
We've seen that modules contain variables which can refer to functions or values. Something to be aware of is that they can also have variables referring to other modules.
다른 함수나 값을 참조하고 있는 변수를 모듈이 가지고 있는 경우가 있다. (#앞서 이야기한 것과 같이 아래에 계층 구조를 가지게 된다. 거의 모든 모듈이 그러하다.)

...
So if we import numpy as above, then calling a function in the random "submodule" will require two dots.
그래서 우리가 numpy를 import 하게 되면 numpy에 속한 함수인 random이 있고 그 아래에서 참조 가능한 여러 함수를 쓸수 있다. 계층의 하부구조에 속한다는 의미에서 sub-module 서브 모듈이라고 부르기도 한다.

..
So after 6 lessons, you're a pro with ints, floats, bools, lists, strings, and dicts (right?).
앞선 강의에서 이미 int, float, bool,, list, string, dict등을 많이 봐왔을 것이다.

Even if that were true, it doesn't end there. As you work with various libraries for specialized tasks, you'll find that they define their own types which you'll have to learn to work with.
앞으로 이외에도 다양한 라이브러리, 모듈을 접할텐데, 각각 정의된 타입과 사용법을 참조할 수 있다.

For example, if you work with the graphing library matplotlib, you'll be coming into contact with objects it defines which represent Subplots, Figures, TickMarks, and Annotations. pandas functions will give you DataFrames and Series.
예를 들어, 그래프와 관련하여 matplotlib 라는 라이브러리르 사용한다면, subplot, ifgures, tickmakrs, annotation 등의 객체를 접하게되고 pandas를 사용하면 dataframe이나 series와 같은 데이터 형을 접하게 된다.

In this section, I want to share with you a quick survival guide for working with strange types.
여기서는 이런 이상한 타입의 라이브러리를 접했을때의 서바이벌 가이드를 주려고 한다.

Three tools for understanding strange objects
In the cell above, we saw that calling a numpy function gave us an "array". We've never seen anything like this before (not in this course anyways). But don't panic: we have three familiar builtin functions to help us here.
위의 numpky에서 우리는 'array'라는 함수를 보게 된다. 이 코스에서는 다룬적이 없는 메소드 인데 놀라지말고 우리를 도와줄 3가지 내장 함수를 소개한다.


1: type() (what is this thing?)
2: dir() (what can I do with it?)
3: help()
...
Operator overloading
연산자 오버 로딩 (연산자 덮어 씌우기)
What's the value of the below expression?
아래 수식의 계산 결과는 무엇인가?
[3, 4, 1, 2, 2, 1] + 10
----> 1 [3, 4, 1, 2, 2, 1] + 10
하지만 아래는 어떨까
...

We might think that Python strictly polices how pieces of its core syntax behave such as +, <, in, ==, or square brackets for indexing and slicing. But in fact, it takes a very hands-off approach. When you define a new type, you can choose how addition works for it, or what it means for an object of that type to be equal to something else.
파이썬이 사칙 연산이나 논리 연산에 대해 엄격한 문법적 규칙을 지니고 있다고 생각하겠지만 상당히 유연한 태도를 갖는다. 우리가 새로운 변수를 정의하면 우리는 그 변수의 작동 방식이나 등가가 무엇인지를 정할 수 있다.

The designers of lists decided that adding them to numbers wasn't allowed. The designers of numpy arrays went a different way (adding the number to each element of the array).
(앞서 공부한) 리스트 데이터 타입을 디자인한 사람은 그냥 숫자를 더할 수 없게 했다. 한편 array를 디자인한 사람은 각 요소에 숫자를 더하는 다른 방식을 택했다.

Here are a few more examples of how numpy arrays interact unexpectedly with Python operators (or at least differently from lists).
아래는 numpy의 array가 파이썬의 연산자와 어떻게 작동하는지의 몇가지 사례다.

....
numpy's ndarray type is specialized for working with multi-dimensional data, so it defines its own logic for indexing, allowing us to index by a tuple to specify the index at each dimension.
numpy의 ndarray 타입은 다차원 데이터와 연계하기 위해 특별히 고안된 것이며, 인덱싱에 대해서도 고유의 로직이 있다. (각 차원에서 튜플로 인덱싱.)

When does 1 + 1 not equal 2?
Things can get weirder than this. You may have heard of (or even used) tensorflow, a Python library popularly used for deep learning. It makes extensive use of operator overloading.
1+1이 2가 아닌 경우가 발생하기도 한다. 사실 이보다 더 이상한 일이 발생할 수도 있다. 파이썬 라이브러리가 딥러닝을 배우는 출발점이 되게 해준 아주 유명한 라이브러리인 tensorflow라는 파이썬라이브러리를 들어봐씅ㄹ 것이다. 이 tensorflow는 매우 다양한 operator의 함수 덮어쓰기를 볼 수 있다.
...
a symbolic handle to one of the outputs of an Operation. It does not hold the values of that operation's output, but instead provides a means of computing those values in a TensorFlow tf.Session.
결과값을 지정한 심볼에 지나지 않으며 tf.Session 내에서 값이 지난 의미를 전달.

It's important just to be aware of the fact that this sort of thing is possible and that libraries will often use operator overloading in non-obvious or magical-seeming ways.
정말 중요한 것은 이런일이 가능하며 많은 라이브러리가 종종 operator로 햐여금 매우 특별한 방법으로 값을 오버로딩하도록 허용

Understanding how Python's operators work when applied to ints, strings, and lists is no guarantee that you'll be able to immediately understand what they do when applied to a tensorflow Tensor, or a numpy
ndarray, or a pandas DataFrame.
int, string, list등 파이썬의 기본 라이브러리에서 연산자가 어떻게 작동하는지 안다고 해도 , tensorflow나 numpy등에서 어떻게 작동하는지 바로 알기 어렵다.

이하 생략
.........

Curious how it all works?
Have you ever called help() or dir() on an object and wondered what the heck all those names with the double-underscores were?
help()나 dir()로 객체에 대해서 사용해봤다면 이 언더 스코어가 같이 쓰인 변수들이 뭘 의미하는지 궁금할 것. (언더바, 언더스코어 '_')
......
This turns out to be directly related to operator overloading.
이것들은 연산자 오버로딩과 직접적인 관련이 있음

When Python programmers want to define how operators behave on their types, they do so by implementing methods with special names beginning and ending with 2 underscores such as __lt__, __setattr__, or __contains__. Generally, names that follow this double-underscore format have a special meaning to Python.
파이썬 프로그래머가 자신들이 정의한(?) 변수 타입에 대해 연산자 작동 방향을 특정하고 싶을때 사전에 미리 정의된 특별한 메소드를 사용하고 이것들이 앞뒤로 언더스코어 두개를 이어 붙인 형태를 가진다.
예를 들어 __lt__, __setattr__, 또는 __contains__와 같은 거다. 이 더블 언더 스코어 포맷을 따르는 변수는 대체로 파이썬에 특별한 의미를 지닌 변수라고 보면 된다.

So, for example, the expression x in [1, 2, 3] is actually calling the list method __contains__ behind-the-scenes. It's equivalent to (the much uglier) [1, 2, 3].__contains__(x).

예를 들어, x in [1,2,3]에서 이 리스트는 사실 __contains__라는 메소드를 호출하고 있지만, 그것이 숨겨져 있을 뿐이다. 이것은 [1,2,3].__contains__(x)와 같다.


If you're curious to learn more, you can check out Python's official documentation, which describes many, many more of these special "underscores" methods.
이에 대해서 추가적인 사항은 파이썬 공식 문서를 참조.



(이하 생략.)