시작하기
설치와 기초
TensorFlow 2.x는 기본적으로 즉시 실행(eager) 모드로 동작합니다(일반 Python처럼 연산이 바로 실행됨). tf.config.list_physical_devices('GPU')로 CUDA GPU가 보이는지 확인하세요. GPU 지원은 Linux/Windows에서 [and-cuda] 추가 패키지를 설치하거나 Apple Silicon에서는 tensorflow-metal을 사용하세요. TF 2.x는 Keras를 tf.keras로 통합했으며 대부분의 워크플로에서 쓰는 고수준 API입니다.
# install TensorFlow (CPU)
pip install tensorflow
# with GPU support on Linux/Windows (CUDA-enabled)
pip install tensorflow[and-cuda]
import tensorflow as tf
# check version and devices
print(tf.__version__)
print("GPU:", tf.config.list_physical_devices('GPU'))
# eager execution is on by default in TF2
print(tf.executing_eagerly()) # True첫 텐서
tf.constant는 불변 텐서를 만들고 tf.zeros / tf.ones / tf.random.*은 흔한 패턴을 만듭니다. 모든 텐서에는 shape, dtype, rank가 있습니다. .numpy()는 NumPy로 되돌리는 다리이며 GPU에서는 동기 복사를 유발할 수 있습니다. ML의 기본값인 float32 같은 명시적 dtype을 사용해 성능을 깨는 조용한 업캐스트를 피하세요.
import tensorflow as tf
# constants are immutable
x = tf.constant([[1, 2], [3, 4]])
y = tf.zeros((3, 3))
z = tf.random.normal((2, 3), mean=0.0, stddev=1.0)
print(x.shape, x.dtype) # (2, 2) int32
print(tf.reduce_sum(x)) # tf.Tensor(10, shape=(), dtype=int32)
# numpy interop is zero-copy when possible
print(x.numpy()) # array([[1, 2], [3, 4]])즉시 실행과 기울기
즉시 실행은 TF를 일반 Python처럼 디버깅 가능하게 합니다. print, pdb, 트레이스백이 모두 동작합니다. GradientTape는 감시 대상 텐서(tf.Variable은 자동 감시)의 순전파 연산을 기록해 tape.gradient가 미분을 계산하게 합니다. 커스텀 학습 루프의 기반입니다. tape는 기본적으로 일회용이므로 gradient를 여러 번 호출하려면 persistent=True를 사용하세요.
import tensorflow as tf
a = tf.constant(3.0)
b = tf.constant(4.0)
print(a * b + 1) # tf.Tensor(13.0, ...)
# GradientTape records ops for automatic differentiation
with tf.GradientTape() as tape:
tape.watch(a)
y = a ** 2 + b # y = a^2 + b, dy/da = 2a
grad = tape.gradient(y, a)
print(grad) # tf.Tensor(6.0, ...) (= 2*3)tf.function과 그래프
@tf.function은 Python 함수를 이식 가능하고 최적화 가능한 TensorFlow 그래프로 변환합니다. GPU에서 훨씬 빠르고 분산에 필요합니다. 함수는 입력 시그니처마다 한 번 추적되므로 Python 부수 효과나 데이터 의존적 Python 제어 흐름을 피하세요(tf.cond / tf.while_loop를 쓰지 않으면 함수가 다시 추적됨). 변수는 함수 밖에서 한 번 만들어야 하며, 아니면 같은 이름으로 tf.Variable을 재사용하세요.
import tensorflow as tf
@tf.function # traces a graph; runs in graph mode after first call
def train_step(x, y):
with tf.GradientTape() as tape:
preds = x * w + b
loss = tf.reduce_mean((preds - y) ** 2)
grads = tape.gradient(loss, [w, b])
optimizer.apply_gradients(zip(grads, [w, b]))
return loss
w = tf.Variable(0.1)
b = tf.Variable(0.0)
optimizer = tf.keras.optimizers.SGD(0.01)
# first call builds the graph (slower); subsequent calls are fast
loss = train_step(tf.constant([1., 2.]), tf.constant([2., 4.]))혼합 정밀도
혼합 정밀도는 float16으로 계산하되 float32 마스터 복사본을 유지해 Tensor Core GPU(Volta+)에서 2-3배 처리량과 절반 메모리를 얻습니다. 'mixed_float16' 정책은 언더플로를 막기 위해 손실 스케일링을 자동 처리합니다. 수치 안정성을 위해 출력 레이어는 float32로 강제하세요. 컴퓨트 능력 7.0 이상이 필요하며 구형 GPU에서는 더 느릴 수 있습니다.
import tensorflow as tf
# enable mixed precision: compute in float16, store in float32
tf.keras.mixed_precision.set_global_policy('mixed_float16')
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', dtype='float32'),
tf.keras.layers.Dense(10, activation='softmax', dtype='float32')
])
# loss scaling is automatic with mixed_float16 policy
print(tf.keras.mixed_precision.global_policy())텐서
tf.constant
tf.constant는 불변 텐서를 만듭니다. 요소에 할당할 수 없습니다. 학습 가능한 텐서에는 tf.Variable을 사용하세요. tf.random.normal/uniform은 재현성을 위해 seed 인자를 받습니다. tf.random.set_seed(42)는 프로그램 전체를 재현 가능하게 합니다. 다차원 생성에는 int가 아닌 shape 튜플을 사용해 예상 밖 동작을 피하세요.
import tensorflow as tf
a = tf.constant([1, 2, 3])
b = tf.constant([[1.0, 2.0], [3.0, 4.0]], dtype=tf.float32)
zeros = tf.zeros((2, 3))
ones = tf.ones((3, 3))
eye = tf.eye(3)
full = tf.fill((2, 3), 7.0)
arange = tf.range(0, 10, 2) # [0, 2, 4, 6, 8]
linspace = tf.linspace(0.0, 1.0, 5)
rand = tf.random.uniform((2, 3))
randn = tf.random.normal((2, 3))
# constants are immutable: a[0] = 5 -> TypeErrortf.Variable
tf.Variable은 모델 매개변수와 옵티마이저 상태에 쓰는 가변 텐서 래퍼입니다. assign / assign_add / assign_sub는 제자리에서 갱신합니다. 일반 Python 할당(w = w + 1)은 새 텐서를 만들고 변경하지 않습니다. Variable은 GradientTape가 자동 감시하지만 tf.constant는 tape.watch()를 명시해야 합니다. Variable은 이를 사용하는 연산과 같은 장치에 두세요.
import tensorflow as tf
w = tf.Variable(0.1, dtype=tf.float32)
W = tf.Variable(tf.random.normal((3, 4)))
b = tf.Variable(tf.zeros((4,)))
# read value
print(w.numpy()) # 0.1
# update value
w.assign(0.5)
w.assign_add(0.1) # w += 0.1
w.assign_sub(0.05)
# assign in place on a slice
W[0, 0].assign(99.0)
# watched by GradientTape automatically
with tf.GradientTape() as tape:
y = w ** 2
grad = tape.gradient(y, w) # 2w텐서 연산
대부분의 수학은 NumPy와 같습니다. tf.reduce_sum / reduce_mean / reduce_max는 np.sum/mean/max에 대응합니다. axis=로 특정 차원을 줄이고 keepdims=True로 브로드캐스팅을 위해 rank를 보존하세요. tf.matmul과 @ 연산자는 행렬 곱을 합니다(입력이 3D 이상이면 배치 처리). reshape는 가능하면 뷰를 반환하고 transpose는 TF에서 항상 복사본을 반환합니다.
import tensorflow as tf
a = tf.constant([[1.0, 2.0], [3.0, 4.0]])
b = tf.constant([[5.0, 6.0], [7.0, 8.0]])
a + b; a - b; a * b; a / b # element-wise
c = tf.matmul(a, b) # matrix multiply
c = a @ b # equivalent
tf.reduce_sum(a) # sum of all
tf.reduce_sum(a, axis=0) # sum along axis 0
tf.reduce_mean(a, axis=1) # mean along axis 1
tf.reduce_max(a, axis=1)
tf.reduce_sum(a, axis=1, keepdims=True)
x = tf.range(12)
y = tf.reshape(x, (3, 4))
t = tf.transpose(y) # shape (4, 3)인덱싱과 슬라이싱
TF는 즉시 실행 모드와 tf.function 안에서 NumPy 스타일 슬라이싱을 지원합니다. tf.boolean_mask는 마스크가 True인 요소를 추출합니다(평탄화). tf.gather는 기본적으로 axis 0을 따라 선택합니다(팬시 인덱싱). tf.where(cond, x, y)는 벡터화된 삼항 연산입니다. cond가 True면 x, 아니면 y를 고릅니다. 할당에는 tf.tensor_scatter_nd_update나 tf.Variable을 사용하세요.
import tensorflow as tf
x = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
x[0] # first row
x[1, 2] # element (1,2) -> 6
x[:, 1] # second column
x[0:2] # first two rows
x[:, ::2] # every other column
# boolean mask
mask = x > 4
sel = tf.boolean_mask(x, mask) # tensor([5, 6, 7, 8, 9])
# gather by indices
idx = tf.constant([0, 2])
rows = tf.gather(x, idx) # rows 0 and 2
# where: select from two tensors
tf.where(x > 4, x, tf.zeros_like(x))Ragged와 Sparse 텐서
Ragged 텐서는 패딩 없이 가변 길이 시퀀스를 저장하므로 길이가 다른 NLP 배치에 완벽합니다. Sparse 텐서는 0이 아닌 인덱스와 값만 저장해 매우 희소한 데이터(추천, 그래프)의 메모리를 절약합니다. 대부분의 연산에 희소 인식 변형이 있으므로 연산이 요구할 때만 dense로 변환하세요. tf.RaggedTensor.to_tensor()는 임베딩 조회를 위해 사각형으로 패딩합니다.
import tensorflow as tf
# ragged: variable-length sequences
ragged = tf.ragged.constant([[1, 2, 3], [4], [5, 6]])
print(ragged.shape) # (3, None)
ragged.to_tensor() # pad to (3, 3)
# sparse: mostly-zero tensors
indices = [[0, 0], [1, 2], [2, 1]]
values = [1.0, 2.0, 3.0]
sparse = tf.sparse.SparseTensor(
indices=indices, values=values, dense_shape=[3, 3])
dense = tf.sparse.to_dense(sparse)
sp_sum = tf.sparse.reduce_sum(sparse)
sp_matmul = tf.sparse.sparse_dense_matmul(sparse, tf.eye(3))브로드캐스팅과 수학
브로드캐스팅은 작은 차원의 텐서를 큰 것과 맞게 요소별로 늘립니다. clip_by_value는 TF의 클 램프입니다. tf.maximum/minimum은 요소별이며 차원을 줄이는 tf.reduce_max/min과 다릅니다. cumsum/cumprod는 축을 따라 누적 합/곱을 생성해 누적 지표와 커스텀 레이어의 접두사 합 알고리즘에 유용합니다.
import tensorflow as tf
# broadcasting follows NumPy rules
a = tf.constant([[1.0, 2.0, 3.0]]) # shape (1, 3)
b = tf.constant([[10.0], [20.0]]) # shape (2, 1)
c = a + b # shape (2, 3)
tf.abs(x); tf.sqrt(x); tf.exp(x); tf.log(x)
tf.square(x); tf.pow(x, 3)
tf.maximum(a, b); tf.minimum(a, b)
tf.clip_by_value(x, 0.0, 1.0)
tf.norm(x) # L2 norm
tf.norm(x, ord=1) # L1 norm
tf.cumsum(tf.range(5)) # [0, 1, 3, 6, 10]
tf.cumprod(tf.range(1, 5)) # [1, 2, 6, 24]Keras 모델
Sequential API
Sequential은 가장 단순한 Keras 모델입니다. 각 레이어 출력이 다음으로 이어지는 선형 파이프라인입니다. input_shape는 배치 차원을 제외합니다(가변 배치는 None). model.summary()는 레이어 모양과 매개변수 수를 출력합니다. input_shape를 넘기지 않으면 첫 fit/순전파 호출에서 지연 생성되므로 더 일찍 확인하려면 build()를 명시 호출하세요.
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(784,)),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax'),
])
model.summary()
# build later with input_shape (or first call)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10))
model.build((None, 784)) # None = variable batchFunctional API
Functional API는 레이어가 분기, 병합, 건너뛰기를 할 수 있게 하므로 비선형 구조(ResNet, 다중 입력/출력, 샴 네트워크)에 필요합니다. Input 텐서를 정의하고 레이어를 호출해 연결한 뒤 inputs/outputs를 Model에 넘기세요. 결과 모델은 fit/predict에서 Sequential과 동일하게 동작합니다. 깔끔한 저장과 서빙 시그니처를 위해 입출력에 이름을 붙이세요.
import tensorflow as tf
inputs = tf.keras.Input(shape=(784,), name='img')
x = tf.keras.layers.Dense(128, activation='relu')(inputs)
x = tf.keras.layers.Dropout(0.5)(x)
x = tf.keras.layers.Dense(64, activation='relu')(x)
outputs = tf.keras.layers.Dense(10, activation='softmax')(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs, name='mlp')
# multi-input / multi-output
img_in = tf.keras.Input(shape=(224, 224, 3))
meta_in = tf.keras.Input(shape=(10,))
x = tf.keras.layers.Conv2D(32, 3, activation='relu')(img_in)
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.concatenate([x, meta_in])
out = tf.keras.layers.Dense(1, activation='sigmoid')(x)
model = tf.keras.Model([img_in, meta_in], out)모델 서브클래싱
tf.keras.Model을 서브클래싱하면 순전파를 완전히 제어할 수 있습니다(PyTorch처럼). __init__에서 레이어를 정의하고 call(inputs, training=)을 구현하세요. training 플래그는 드롭아웃과 BatchNorm 동작을 토글합니다. 유연하지만 Functional API의 이점 일부를 잃습니다. 검사/시각화가 어렵고 자동 입력 모양 추론이 없으며 직렬화가 까다롭습니다. 대부분의 아키텍처에는 Functional을, 연구 모델에는 서브클래싱을 권장하세요.
import tensorflow as tf
class MLP(tf.keras.Model):
def __init__(self, hidden=128, num_classes=10):
super().__init__()
self.dense1 = tf.keras.layers.Dense(hidden, activation='relu')
self.drop = tf.keras.layers.Dropout(0.5)
self.dense2 = tf.keras.layers.Dense(hidden, activation='relu')
self.out = tf.keras.layers.Dense(num_classes, activation='softmax')
def call(self, inputs, training=False):
x = self.dense1(inputs)
x = self.drop(x, training=training)
x = self.dense2(x)
return self.out(x)
model = MLP(hidden=64)
model.build((None, 784))
model.summary()모델 컴파일
compile은 fit 전에 옵티마이저, 손실, 지표를 연결합니다. 문자열('adam', 'mse')은 해당 클래스의 단축이며 사용자 정의 하이퍼파라미터에는 객체를 넘기세요. 다중 출력 모델에는 출력 이름을 손실에 매핑한 딕셔너리를 넘기세요. run_eagerly=True는 tf.function 추적을 꺼서 pdb와 print를 쓸 수 있게 하므로 디버깅에 매우 유용하지만 느립니다.
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
loss_weights={'cls': 1.0, 'box': 0.5},
)
# explicit objects (more control)
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy(name='acc')],
run_eagerly=False, # debug mode: run without graph
)모델 요 약과 플롯
summary()는 레이어별 출력 모양과 매개변수 수 표를 출력하므로 모양 버그를 찾는 가장 빠른 방법입니다. plot_model은 시각적 그래프를 저장합니다(pydot와 Graphviz 필요). get_config는 가중치 없이 아키텍처를 재구성할 수 있는 직렬화 딕셔너리를 반환하며 model.to_json()과 Keras 저장 형식이 사용합니다. Functional 모델은 config가 아키텍처를 완전히 담지만 서브클래싱 모델은 get_config를 직접 구현해야 합니다.
model.summary()
print(model.layers)
print(model.inputs, model.outputs)
# plot architecture (needs pydot + graphviz)
tf.keras.utils.plot_model(
model, to_file='model.png', show_shapes=True,
show_layer_names=True, rankdir='TB',
)
print(f"{model.count_params():,} params")
config = model.get_config()
new_model = tf.keras.Model.from_config(config)모델 내 전처리
전처리를 모델 안에 넣으면(Rescaling, 증강 Keras 레이어) 배포 가능해집니다. 같은 SavedModel이 추론 시 원시 이미지를 받아 별도 전처리 단계가 필요 없습니다. Keras 전처리 레이어는 GPU와 tf.function 안에서 실행되어 빠릅니다. 학습 전용 증강은 fit에서 training=True로 설정해 추론 시 비활성화하세요. Rescaling(1./255)은 uint8 [0,255] 이미지를 float [0,1]로 변환합니다.
import tensorflow as tf
# preprocessing as part of the model (deployable)
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(224, 224, 3)),
tf.keras.layers.Rescaling(1./255),
tf.keras.layers.RandomFlip('horizontal'),
tf.keras.layers.RandomRotation(0.1),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
# ...
])
# the model now includes preprocessing, so inference needs raw images레이어
Dense 레이어
Dense는 완전 연결 레이어입니다: y = activation(xW + b). 가중치 모양은 (in_features, out_features)로 PyTorch의 전치입니다. kernel_initializer는 기본 Glorot/Xavier uniform이라 tanh/sigmoid에 좋고 ReLU 계열에는 'he_normal'을 사용하세요. kernel_regularizer로 L2 정규화를 추가하세요. GELU는 트랜스포머의 기본 활성화입니다.
import tensorflow as tf
dense = tf.keras.layers.Dense(
units=64, activation='relu', use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=tf.keras.regularizers.l2(1e-4),
)
x = tf.random.normal((4, 128))
y = dense(x) # shape (4, 64)
print(dense.kernel.shape) # (128, 64)
print(dense.bias.shape) # (64,)
dense = tf.keras.layers.Dense(64, activation=tf.nn.gelu)Conv2D 레이어
TF/Keras는 PyTorch의 NCHW와 반대로 기본 NHWC(channels-last)를 사용합니다. padding='same'은 출력 공간 크기가 입력 크기 / stride가 되도록 패딩하고 'valid'는 패딩이 없습니다. DepthwiseConv2D는 입력 채널마다 필터 하나를 적용합니다(MobileNet에서 사용). Conv2DTranspose는 업샘플링합니다(분할 디코더에서 사용). 커널 모양은 (kH, kW, in_channels, filters)입니다.
import tensorflow as tf
conv = tf.keras.layers.Conv2D(
filters=32, kernel_size=3, strides=(1, 1),
padding='same', activation='relu', use_bias=True,
)
x = tf.random.normal((4, 28, 28, 3)) # NHWC
out = conv(x)
print(out.shape) # (4, 28, 28, 32) with padding='same'
dw = tf.keras.layers.DepthwiseConv2D(3, padding='same', activation='relu')
up = tf.keras.layers.Conv2DTranspose(32, 3, strides=2, padding='same')순환 레이어(LSTM/GRU)
RNN의 입력 모양은 (batch, timesteps, features)입니다. RNN을 쌓거나 시퀀스-투-시퀀스 모델을 만들 때 return_sequences=True가 필요하고 시퀀스-투-벡터에는 False입니다. Bidirectional은 순방향과 역방향 출력을 연결해 출력 크기를 두 배로 만듭니다. recurrent_dropout은 편리하지만 느립니다(cuDNN 가속 없음). 대신 입력에 일반 드롭아웃을 권장하세요.
import tensorflow as tf
lstm = tf.keras.layers.LSTM(units=128, return_sequences=False)
x = tf.random.normal((4, 10, 64)) # (batch, time, features)
out = lstm(x) # (4, 128)
# stacked LSTM needs return_sequences=True
model = tf.keras.Sequential([
tf.keras.layers.LSTM(128, return_sequences=True, input_shape=(10, 64)),
tf.keras.layers.LSTM(64),
tf.keras.layers.Dense(10),
])
gru = tf.keras.layers.GRU(128)
bi = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64))
out = bi(x) # shape (4, 128) — 64 * 2드롭아웃과 정규화
Dropout은 학습 중 유닛을 무작위로 0으로 만들어 공동 적응을 막고 추론 시(training=False) 자동 비활성화됩니다. SpatialDropout2D는 특징 맵 전체를 드롭해 합성곱 신경망에 더 좋습니다. L2(가중치 감쇠)는 가장 흔한 정규화입니다. LayerNormalization은 배치 축이 아니라 특징 축(샘플별)으로 정규화하므로 트랜스포머와 RNN에 선호됩니다(BatchNorm과 대조).
import tensorflow as tf
drop = tf.keras.layers.Dropout(0.5)
x = tf.random.normal((4, 10))
y = drop(x, training=True) # training=True activates dropout
tf.keras.layers.SpatialDropout2D(0.5) # drop entire feature maps
tf.keras.layers.GaussianDropout(0.5)
tf.keras.layers.AlphaDropout(0.5)
# weight regularization
tf.keras.layers.Dense(64,
kernel_regularizer=tf.keras.regularizers.l2(1e-4),
activity_regularizer=tf.keras.regularizers.l1(1e-5))
norm = tf.keras.layers.LayerNormalization()배치 정규화
BatchNormalization은 채널별로 활성화를 정규화하고 추론용 EMA 실행 통계를 유지합니다. NHWC에서 axis=-1은 마지막(채널) 축을 정규화합니다. BN은 합성곱 뒤, 활성화 앞에 두고 BN의 beta가 이동을 처리하므로 합성곱의 bias를 끄세요(use_bias=False). momentum은 실행 통계가 데이터를 얼마나 빨리 따라가는지 제어하며 높은 값(0.99)이 더 안정적입니다. BN은 학습과 추론에서 다르게 동작합니다(training 플래그).
import tensorflow as tf
bn = tf.keras.layers.BatchNormalization(
axis=-1, momentum=0.99, epsilon=1e-3,
)
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, padding='same', use_bias=False),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.ReLU(),
])
print(len(bn.weights)) # 4
print(len(bn.trainable_weights)) # 2커스텀 레이어
Layer를 서브클래싱해 커스텀 연산을 만드세요. 가중치는 __init__이 아니라 build()(입력 모양과 함께 한 번 호출)에서 정의해 입력 크기에 적응하게 하세요. get_config()를 구현해 레이어를 직렬화하고 다시 로드할 수 있게 하세요. add_weight는 텐서를 Keras 추적에 등록해 weights에 나타나고 저장되며 장치로 이동하게 합니다. 상태 없는 변환은 build()를 생략하고 call()만 재정의할 수 있습니다.
import tensorflow as tf
class Linear(tf.keras.layers.Layer):
def __init__(self, units=32, **kwargs):
super().__init__(**kwargs)
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer='glorot_uniform', trainable=True, name='w')
self.b = self.add_weight(
shape=(self.units,), initializer='zeros', trainable=True, name='b')
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
def get_config(self):
config = super().get_config()
config.update({'units': self.units})
return config
layer = Linear(64)
out = layer(tf.random.normal((4, 10)))손실
BinaryCrossentropy
BinaryCrossentropy는 이진 작업이나 다중 레이블(각 클래스 독립)에 사용합니다. 모델이 원시 로짓을 출력하면 from_logits=True를 넘기세요. sigmoid + BCE를 따로 적용하는 것보다 수치적으로 안전합니다. pos_weight는 양성 예제의 가중치를 높여 불균형을 처리합니다. C개 클래스의 다중 레이블 문제에서 타깃 모양은 0/1의 (N, C)이고 예측은 (N, C) 확률 또는 로짓입니다.