본문 바로가기
First step/AI 기초반

[TIL]21.07.02tensorflow 1.x버젼으로 tensor 이해하기

by Joshua21 2021. 7. 2.

tensorflow를 사용해서 경사하강법을 적용하기전에 numpy등을 활용해서 데이터를 가지고 기울기와 y절편값 즉 wight,bais를 찾는 법을 연습했다.

 

#연습문제 경사하강법-텐서플로우 미사용
import numpy as np 
import pandas as pd
import matplotlib.pyplot as plt

data=[[2,81],[4,93],[6,91],[8,97]]
x=[i[0] for i in data]
y=[i[1] for i in data]

plt.figure(figsize=(8,5)) #figre 기름 그릴 영역을 나타내는 객체를 만들어주고 편집할수있게해줌
plt.scatter(x,y) #연속형 변수의 산점도 그래프를 표현하는 함수
plt.show()#메모리상에 정리된 차트를 실제 화면에 보여줌

x_data=np.array(x) #x,y가 리스트라면 정수인 b와 연산이 불가함으로 array
y_data=np.array(y)

a=0
b=0

lr=0.01 #학습률 정하기

#몇번 반복될지 설정(0부터 세므로 원하는 반복횟수에 +1)
epochs=2001

#경사 하강법 시작
for i in range(epochs):
    
    y_pred = a*x_data +b #y를 구하는 식 세우기
    error = y_data - y_pred #오차를 구하는 식
    #오차 함수를 a 로 미분한값
    a_diff = -(1/len(x_data))*sum(x_data*(error))
    #오차 함수를 b 로 미분한값
    b_diff=- -(1/len(x_data))* sum(error) 
    #공식대로 코드를 짰을경우
    a_diff = 2/len(x_data)*sum((a*x_data+b-y_data)*x_data)
    b_diff= 2/len(x_data)*sum((a*x_data+b-y_data))

    a = a-lr*a_diff #학습률을 곱해 기존의 a값 업데이트
    b = b-lr*b_diff #학습률을 곱해 기존의 b값 업데이트
    
    if i%100 ==0: #100번 반복될 때마다 현재의 a,b값 출력
        print('epoch=%.f, 기울기=%.04f, 절편==%.04f'%(i,a,b))

#앞서 구한 기울기와 절편을 이용해 그래프를 다시그리기    
y_pred=a*x_data +b
plt.scatter(x,y)
plt.plot([min(x_data),max(x_data)],[min(y_pred),max(y_pred)])
plt.show()

 

import numpy as np 
import pandas as pd
import matplotlib.pyplot as plt

data=[[1,0.2],[2,0.3],[3,0.5],[4,0.6],[5,0.9],[6,0.95],[7,1.1],[8,1.5]]

x=[i[0] for i in data]
y=[i[1] for i in data]

plt.figure(figsize=(8,5)) #figre 기름 그릴 영역을 나타내는 객체를 만들어주고 편집할수있게해줌
plt.scatter(x,y) #연속형 변수의 산점도 그래프를 표현하는 함수
plt.show()


x_data=np.array(x) 
y_data=np.array(y)
a=0
b=0

lr=0.03

epochs=2001

for i in range(epochs):
    y_pred=a*x_data +b
  
    a_diff=2/len(x_data)*sum((a*x_data+b-y_data)*x_data)
    b_diff=2/len(x_data)*sum((a*x_data+b-y_data))
    
    a= a - lr*a_diff
    b= b - lr*b_diff
    
    if i%100 ==0:
        print('epoch=%.f, 기울기=%.04f, 절편==%.04f'%(i,a,b))

y_pred=a*x_data +b
plt.scatter(x,y)
plt.plot([min(x_data),max(x_data)],[min(y_pred),max(y_pred)])
plt.show()

 

lr 런닝메이트는 하이퍼파라미터 이므로 정해져있거나 유도할수있는 공식은 없다 

 

import numpy as np 
import pandas as pd
import matplotlib.pyplot as plt

data=[[1,0.2],[2,0.3],[3,0.5],[4,0.6],[5,0.9],[6,0.95],[7,1.1],[8,1.5]]

x=[i[0] for i in data]
y=[i[1] for i in data]

plt.figure(figsize=(8,5)) #figre 기름 그릴 영역을 나타내는 객체를 만들어주고 편집할수있게해줌
plt.scatter(x,y) #연속형 변수의 산점도 그래프를 표현하는 함수
plt.show()


x_data=np.array(x) 
y_data=np.array(y)
a=0
b=0

lr=0.03

epochs=2001

for i in range(epochs):
    y_pred=a*x_data +b
  
    a_diff=2/len(x_data)*sum((a*x_data+b-y_data)*x_data)
    b_diff=2/len(x_data)*sum((a*x_data+b-y_data))
    
    a= a - lr*a_diff
    b= b - lr*b_diff
    
    if i%100 ==0:
        print('epoch=%.f, 기울기=%.04f, 절편==%.04f'%(i,a,b))

y_pred=a*x_data +b
plt.scatter(x,y)
plt.plot([min(x_data),max(x_data)],[min(y_pred),max(y_pred)])
plt.show()

 

#웹상에서 데이터 구해서 실습하기
import numpy as np 
import pandas as pd
import matplotlib.pyplot as plt
#79~04년까지 30대후반 남성의 평균 bmi변화 실측값으로 
data=[[1986,22.2],[1992,22.7],[1997,23.1],[2004,23.6],[2010,24],[2015,24.5]]
#data=[[1,22.1],[8,22.2],[14,22.7],[19,23.1],[26,23.6],[32,24],[37,24.5]]

x=[i[0] for i in data]
y=[i[1] for i in data]

plt.figure(figsize=(8,5)) #figre 기름 그릴 영역을 나타내는 객체를 만들어주고 편집할수있게해줌
plt.scatter(x,y) #연속형 변수의 산점도 그래프를 표현하는 함수
plt.show()


x_data=np.array(x) 
y_data=np.array(y)
a=0
b=0

lr=0.000002

epochs=101

for i in range(epochs):
    y_pred=a*x_data +b
  
    a_diff=2/len(x_data)*sum((a*x_data+b-y_data)*x_data)
    b_diff=2/len(x_data)*sum((a*x_data+b-y_data))
    
    a= a - lr*a_diff
    b= b - lr*b_diff
    
    if i%10 ==0:
        print('epoch=%.f, 기울기=%.04f, 절편==%.04f'%(i,a,b))

y_pred=a*x_data +b
plt.scatter(x,y)
plt.plot([min(x_data),max(x_data)],[min(y_pred),max(y_pred)])
plt.show()

 

#tensorflow 사용하기

나의경우 저번 수업때tensorflow 2.3버젼을 수업을 들으며 강사님이 알려주신데로 가상환경을 구축하며 파이썬3.7버젼과 같이 설치하였는데 분명 잘되다가 오늘 수업떄 다시 하려고하니 모듈이 없다고 에러가 발생해서 급한데로 구글코랩으로 이후 수업들 들었다.

 

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

a = tf.constant(7.0, name = 'data1')

b = tf.constant(3.0, name = 'data2')

c = tf.constant(2.0, name = 'data3')

v = a * b / c

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())

    print(sess.run(v))

 

텐서플로우는 node와 edge로 구성괸 그래프로 표현 그래프의 각 nodde들은 operation을 의미한다

 

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

a = tf.constant(5, name = 'data1')

b = tf.constant(3, name = 'data2')

c = tf.multiply(a,b,name='c')

d=tf.add(a,b,name='d')

e=tf.add(c,d,name='e')

 

sess= tf.Session()

print(sess.run(e))

 

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

a = tf.constant(7.0, name = 'data1')

b = tf.constant(3.0, name = 'data2')

c = tf.constant(2.0, name = 'data3')

v = a * b / c

 

print(v)

 

텐서플로의 즉시 실행은 그래프를 생성하지 않고 함수를 바로 실행하는 명령형 프로그래밍 환경

2.x저변부터 즉시실행 활성화 

 

넘파이배열과 텐서의 가장 확연한 차이

텐서는 가속이 메모리 cpu,tpu에서 사용가능

텐서는 pgu메모리에 저장 될수 있고 넘파이 배열은 항상 호스트 메모리에 저장됨 변환이 항상 가능하지는

않지만 일반적으로 텐서는 .numpy 메서드로 넘파이로 변환 가능

텐서는 일관된 유형을 가진 다차원 배열

모든 텐서는 python 숫자 및 문자열과 같이 변경할수 없음

텐서는 rank,shape,type을 가지고있음

랭크가 0이면 스칼라 1이면벡터 2면 행렬 3이상이면 n-tensor

tensoe type은 텐서가 담을수있는 데이터 타입을 의미

텐서플로우의 자료형

tf.constant 변하지 않는 수를 지정하는 자료형

tf.placeholder 먼저 만들고 값을 나중에 지정해주는 자료형

tf.variavle 조건에 따라 값을 바꿔야 하는 경우 사용하는 자료형

 

#여기서 부터 1~2줄씩 각 cell에 실행해가면서 어떤식으로 작동하는지 확인했다.

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

 

tf.get_default_graph().get_operations()

 

 

a = tf.constant(7.0, name = 'data1')

b = tf.constant(3.0, name = 'data2')

c = tf.constant(2.0, name = 'data3')

 

tf.get_default_graph().get_operations()

 

print(a)

print(a.op)

 

 

print(a.op.outputs) #operaion a 의 출력에 접근하여 확인

print(a is a.op.outputs[0])#텐서 a와 operaion 의 출력이 같은지 확인

print(a.op.node_def.attr['value'].tensor.float_val[0])#a의 operation protocol 버퍼에서 출력값을 확인할수있음

 

 

v=a*b/c

tf.get_default_graph().get_operations()

 

print('v.op.outputs=',v.op.outputs)#텐서의 v의 operation의 출력을 확인

 

print(v.op)#텐서 v의 operation의 node를 확인 

 

print(v.op.inputs[0])#텐서 v의 operation의 node input을 확인

print(v.op.inputs[1])

 

 

with tf.Session() as sess:

  sess.run(tf.global_variables_initializer())

  print(sess.run(v))

 

a = tf.constant(5)

b = tf.constant(2)

c = tf.constant(3)

d = tf.multiply(a,b)

e = tf.add(c,b)

f = tf.subtract(d,e)

 

print(a)

print(b)

print(c)

print(d)

print(e)

print(f)

 

sess=tf.Session()

outs=sess.run(f)

sess.close()

print("out=",outs)

 

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

 

hello=tf.constant('hello , Tensorflow!')

 

sess=tf.Session()

 

print(sess.run(hello))

sess.close()

 

 

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

 

input_data=[1,2,3,4,5]

 

x=tf.placeholder(dtype=tf.float32)

y=x*2

 

sess= tf.Session()

result = sess.run(y,feed_dict={x:input_data})

print(result)

 

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

 

p_holder1 = tf.placeholder(dtype=tf.float32)

p_holder2 = tf.placeholder(dtype=tf.float32)

p_holder3 = tf.placeholder(dtype=tf.float32)

 

val1=5

val2=10

val3=3

ret_val=p_holder1*p_holder2+p_holder3

 

sess=tf.Session()

feed_dict_data={p_holder1:val1,p_holder2:val2,p_holder3:val3}

result=sess.run(ret_val, feed_dict=feed_dict_data)

sess.close()

print(result)

 

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

 

I=tf.placeholder(tf.float32,[2,4])

i=[[1,2,3,4],[5,6,7,8]]

 

W=tf.placeholder(tf.float32,[4,2])

w=[[1,1],[2,2],[3,3],[4,4]]

 

#행렬의 곱셈 수행

m_cal=tf.matmul(I,W)



sess=tf.Session()

print(sess.run(m_cal,feed_dict={I:i,W:w}))

sess.close()

 

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

I=tf.Variable([[1,2,3,4],[5,6,7,8]],tf.float32)

W=tf.Variable([[1,1],[2,2],[3,3],[4,4]],tf.float32)

 

m_cal=tf.matmul(I,W)



sess=tf.Session()

sess.run(tf.global_variables_initializer())

print(sess.run(m_cal))

 

sess.close()

 

 

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

 

x=tf.Variable(5,dtype=tf.float32)

print(x)

z=tf.assign(x,7)

# x가 assign 되지 않으면 tf.global_variables_initializer() 반드시해줘야함

sess=tf.Session()

sess.run(z)

 

y= sess.run(x)

 

sess.close()

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

 

x=tf.Variable(tf.zeros((2,2)),dtype=tf.float32)

print(x)

 

y=tf.Variable([[1,2],[3,4]], dtype=tf.float32)

x=tf.assign(x,y)

sess = tf.Session()

z=tf.global_variables_initializer()

sess.run(z)

k=sess.run(x)

sess.close()

 

print(k)

 

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

    

mat_img = [1,2,3,4,5]

label = [1020304050]

ph_img=tf.placeholder(dtype=tf.float32)

ph_lb=tf.placeholder(dtype=tf.float32)

 

ret_tensor=ph_img+ph_lb




sess= tf.Session()

result=sess.run(ret_tensor,feed_dict={ph_img:mat_img, ph_lb:label})

sess.close()

print(result)

 

#행렬 예제

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

 

input_data=[[1.,2.,3.],[1.,2.,3.],[2.,3.,4.]]

x=tf.placeholder(dtype=tf.float32,shape=[None,3])

w=tf.Variable([[2.],[2.],[2.]], dtype=tf.float32)

y=tf.matmul(x,w)

sess=tf.Session()

init=tf.global_variables_initializer()

sess.run(init)

result = sess.run(y,feed_dict={x:input_data})

sess.close()

print(result)

 

 

#브로드 캐스팅 행렬 연산에서 차원이 맞지 않을떄 차원을 늘려줘서 자동으로 맞춰줌(줄이는건x)

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

 

input_data=[[1,1,1],[2,2,2,]]

x=tf.placeholder(dtype=tf.float32,shape=[2,3])

w=tf.Variable([[2],[2],[2]], dtype=tf.float32)

b=tf.Variable([4], dtype=tf.float32)          

y=tf.matmul(x,w)+b

print(x.get_shape())

sess=tf.Session()

init=tf.global_variables_initializer()

sess.run(init)

result = sess.run(y,feed_dict={x:input_data})

sess.close()

print(result)

import tensorflow.compat.v1 as tf 

tf.disable_v2_behavior()

 

x=tf.constant([[1.0,2.0,3.0]])

w=tf.constant([[2.0],[2.0],[2.0]])

y=tf.matmul(x,w)

print(x.get_shape())

print(w.get_shape())

print(y.get_shape())

print(y)

 

sess=tf.Session()

init=tf.global_variables_initializer()

sess.run(init)

result = sess.run(y)

sess.close()

print(result)