DeepLearning / / 2022. 10. 29. 14:20

DeepLearning - Tensorflow 기초(텐서,변수,연산,문자열)

텐서플로우 1버전과 2버전의  차이는 '넘파이' 기능 추가 

#넘파이 텐서
tensor_20 = np.array([[23,4],[32,51]])
tensor_from_np = tf.constant(tensor_20)

print(tensor_from_np)

출력:

tf.Tensor(
[[23  4]
 [32 51]], shape=(2, 2), dtype=int32)

np.array로 (2,2) 행렬을 만든후 출력하면  shape 와 2,2배열 , dtype 정수형 2차원 텐서가 출력된다

 

#Variables 변수

tf2_variable = tf.Variable([[1.,2.,3.],[4.,5.,6.]])
print(tf2_variable.numpy())

출력: 
[[1. 2. 3.]
 [4. 5. 6.]]

만약 variable의 숫자를 변경 하고 싶다면 assign을 이용한다.

#variable 안의 1행 2열의 결과 값을 100으로 변경한다. 3 -> 100

tf2_variable[0, 2].assign(100) 
print(tf2_variable.numpy())

<텐서의 각종 연산>

#2행 2열
tensor = tf.constant([[1, 2], [3, 4]])
print(tensor)

#스칼라 + 텐서 연산 각 열 + 2 
print(tensor +2) 

#스칼라 * 텐서 각 열 *5
print(tensor*5)

#넘파이를 이용한 텐서의 모든 제곱값 구하기 
print(np.square(tensor))

#텐서의 모든 제곱근 구하기 
print(np.sqrt(tensor))

<두 텐서 사이의 행렬 곱셈>

#두 텐서 사이에 행렬 곱셈
 tensor = tf.constant([[1, 2], 
                      [3, 4]])

 tensor_20 = np.array([[23,4],
                      [32,51]]) 
print(np.dot(tensor,tensor_20))
'''
<기초 행렬 곱셈>

87은  (23 x 1) + (32 x2)
106은 (1x4)+ (2x51) 
197은 (3x23)+ (4x32)
216은 (3*4) +(51*4)
'''
#출력 : [[ 87 106]
 #      [197 216]]

String in Tensorflow 나중에 심화 자연어 처리를 위해 다룰 수 있으면 유용하다

tf_string = tf.constant('TensorFlow')
print(tf_string)
#Simple strong operations
#문자열 길이
print(tf.strings.length(tf_string))
#디코딩 unicode_decode 함수는 두개의 요소가 필요하다 

print(tf.strings.unicode_decode(tf_string,'UTF8'))

문자열 배열 저장

#문자열 배열 저장 하는 방법 
tf_string_array = tf.constant(['Tensorflow','Deep Learning','AI'])
#Itering Through the TF string array 
for string in tf_string_array: 
    print(string)
    
'''출력:
tf.Tensor(b'Tensorflow', shape=(), dtype=string)
tf.Tensor(b'Deep Learning', shape=(), dtype=string)
tf.Tensor(b'AI', shape=(), dtype=string)
'''
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유