본문 바로가기
Pytorch/Summarize

1. 텐서(tensor)란?_array와 list를 이용하여 텐서 생성하기

by 소소한 혜밍씨 2022. 8. 24.

numpy ndarray나 python의 list도 tensor로 바꿀 수 있다.

 

 

1. numpy ndarray to tensor

 

먼저 array 를 생성해보자.

 

x_np = np.array([[1.0, 2.0],
                [3.0, 4.0]])

 

앞서 포스팅한 constant 안에 넣어도 되지만 convert_to_tensor 를 사용할 수도 있다.

 

# tf.constant 이용

x_np_1 = tf.constant(x_np)



# convert_to_tensor 이용

x_np_2 = tf.convert_to_tensor(x_np)

 

두 결과의 데이터타입을 확인해보면

 

<class 'tensorflow.python.framework.ops.EagerTensor'>
<class 'tensorflow.python.framework.ops.EagerTensor'>

 

위와 같이 동일한 것을 확인할 수 있다.

 

 

 

 

 

 

2. python list to tensor

 

array 를 단순히 list로 변경만 하면 되므로 코드를 한번에 적용하면 다음과 같다.

 

# list 생성

x_list = [[1.0, 2.0], [3.0, 4.0]]


# tf.constant 이용

x_list_1 = tf.constant(x_list)



# convert_to_tensor 이용

x_list_2 = tf.convert_to_tensor(x_list)


print(type(x_list_1))
print(type(x_list_2))

 

 

 

 

 

 

 

 

'Pytorch > Summarize' 카테고리의 다른 글

1. 텐서(tensor)란?_텐서 생성하기  (0) 2022.08.24

댓글