Programming

Keras 입력 설명 : input_shape, units, batch_size, dim 등

procodes 2020. 5. 19. 20:47
반응형

Keras 입력 설명 : input_shape, units, batch_size, dim 등


어떤 Keras 층 (위해 Layer클래스), 캔 누군가의 차이점을 이해하는 방법을 설명합니다 input_shape, units, dim, 등?

예를 들어 의사는 units레이어의 출력 모양을 지정 한다고 말합니다 .

아래 신경망의 이미지 hidden layer1에는 4 단위가 있습니다. 이것이 객체 units속성으로 직접 번역됩니까 Layer? 아니면 unitsKeras에서 숨겨진 레이어의 모든 가중치의 모양에 단위 수를 곱한 것입니까?

간단히 말해 아래 이미지를 사용하여 모델, 특히 레이어의 속성을 어떻게 이해 / 시각화합니까? 여기에 이미지 설명을 입력하십시오


단위 :

"뉴런"또는 "셀"의 양 또는 레이어 내부에있는 모든 것.

각 레이어의 속성이며 예, 출력 모양과 관련이 있습니다 (나중에 볼 수 있음). 다른 레이어와 개념적으로 다른 입력 레이어를 제외하고 그림에는 다음이 있습니다.

  • 숨겨진 층 1 : 4 단위 (4 뉴런)
  • 숨겨진 레이어 2 : 4 대
  • 마지막 층 : 1 개 단위

모양

모양은 모델 구성의 결과입니다. 셰이프는 배열 또는 텐서가 각 차원에있는 요소 수를 나타내는 튜플입니다.

예 : 모양 (30,4,10)은 3 차원의 배열 또는 텐서를 의미하며, 첫 번째 차원에는 30 개의 요소, 두 번째에는 4 개의 요소, 세 번째에는 10 개의 요소를 포함하며 총 30 * 4 * 10 = 1200 개의 요소 또는 숫자입니다.

입력 모양

층 사이에 흐르는 것은 텐서입니다. 텐서는 모양이있는 행렬로 볼 수 있습니다.

Keras에서 입력 레이어 자체는 레이어가 아니라 텐서입니다. 첫 번째 숨겨진 레이어로 보내는 시작 텐서입니다. 이 텐서는 훈련 데이터와 모양이 같아야합니다.

예 : RGB (3 채널)로 50x50 픽셀의 30 개 이미지가있는 경우 입력 데이터의 모양은입니다 (30,50,50,3). 입력 레이어 텐서는이 모양이어야합니다 ( "케 라스 모양"섹션의 세부 사항 참조).

각 유형의 레이어에는 특정 치수의 입력이 필요합니다.

  • Dense 레이어는 다음과 같이 입력이 필요합니다 (batch_size, input_size)
    • 또는 (batch_size, optional,...,optional, input_size)
  • 2D 컨볼 루션 레이어에는 다음과 같은 입력이 필요합니다.
    • 사용하는 경우 channels_last:(batch_size, imageside1, imageside2, channels)
    • 사용하는 경우 channels_first:(batch_size, channels, imageside1, imageside2)
  • 1D 컨볼 루션 및 반복 레이어 사용 (batch_size, sequence_length, features)

이제 입력 모양은 사용자가 정의 할 수있는 유일한 모양입니다. 모델에서 알 수 없기 때문입니다. 오직 훈련 데이터에 기초하여 당신 만이 알고 있습니다.

All the other shapes are calculated automatically based on the units and particularities of each layer.

Relation between shapes and units - The output shape

Given the input shape, all other shapes are results of layers calculations.

The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).

Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)

Let's show what happens with "Dense" layers, which is the type shown in your graph.

A dense layer has an output shape of (batch_size,units). So, yes, units, the property of the layer, also defines the output shape.

  • Hidden layer 1: 4 units, output shape: (batch_size,4).
  • Hidden layer 2: 4 units, output shape: (batch_size,4).
  • Last layer: 1 unit, output shape: (batch_size,1).

Weights

Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.

In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.

In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.

Shapes in Keras

Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3).

Since the input shape is the only one you need to define, Keras will demand it in the first layer.

But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:

input_shape = (50,50,3)
    #regardless of how many images I have, each image has this shape        

Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3) or batch_shape=(30,50,50,3). This limits your training possibilities to this unique batch size, so it should be used only when really required.

Either way you choose, tensors in the model will have the batch dimension.

So, even if you used input_shape=(50,50,3), when keras sends you messages, or when you print the model summary, it will show (None,50,50,3).

The first dimension is the batch size, it's None because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None)

Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.

  • So, when defining the input shape, you ignore the batch size: input_shape=(50,50,3)
  • When doing operations directly on tensors, the shape will be again (30,50,50,3)
  • When keras sends you a message, the shape will be (None,50,50,3) or (30,50,50,3), depending on what type of message it sends you.

Dim

And in the end, what is dim?

If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim as a scalar number.

So, in your model, where your input layer has 3 elements, you can use any of these two:

  • input_shape=(3,) -- The comma is necessary when you have only one dimension
  • input_dim = 3

But when dealing directly with the tensors, often dim will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.


Defining your image in Keras

Keras has two ways of doing it, Sequential models, or the functional API Model. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.

PS: here I ignored other aspects, such as activation functions.

With the Sequential model:

from keras.models import Sequential  
from keras.layers import *  

model = Sequential()    

#start from the first hidden layer, since the input is not actually a layer   
#but inform the shape of the input, with 3 elements.    
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input

#further layers:    
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer   

With the functional API Model:

from keras.models import Model   
from keras.layers import * 

#Start defining the input tensor:
inpTensor = Input((3,))   

#create the layers and pass them the input tensor to get the output tensor:    
hidden1Out = Dense(units=4)(inpTensor)    
hidden2Out = Dense(units=4)(hidden1Out)    
finalOut = Dense(units=1)(hidden2Out)   

#define the model's start and end points    
model = Model(inpTensor,finalOut)

Shapes of the tensors

Remember you ignore batch sizes when defining layers:

  • inpTensor: (None,3)
  • hidden1Out: (None,4)
  • hidden2Out: (None,4)
  • finalOut: (None,1)

Input Dimension Clarified:

Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:

It (the word dimension alone) can refer to:

a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"

b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or

"Input Layer / Input Feature Dimension"

c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.

"N Dimensionality of Input"

d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:

Keras의 input_dim은 입력 레이어의 차원 / 입력 기능 수를 나타냅니다.

model = Sequential()
model.add(Dense(32, input_dim=784))  #or 3 in the current posted example above
model.add(Activation('relu'))

Keras LSTM에서는 총 시간 단계를 나타냅니다.

이 용어는 매우 혼란스럽고 정확하며 우리는 매우 혼란스러운 세상에 살고 있습니다 !!

기계 학습의 과제 중 하나는 다른 언어 나 방언 및 용어를 다루는 것입니다 (예를 들어, 5-8 개의 매우 다른 영어 버전을 사용하는 경우 다른 스피커와 대화하려면 매우 높은 숙련도가 필요함). 아마도 이것은 프로그래밍 언어에서도 동일합니다.

참고 : https://stackoverflow.com/questions/44747343/keras-input-explanation-input-shape-units-batch-size-dim-etc

반응형