/ LECTURE

Python - Tensorflow

이 페이지는 다음에 대한 공부 기록입니다

JAVA(자바), Python(파이썬) 기반의

AI 활용 응용 소프트웨어 개발자 양성 과정

2021.11.10. ~ 2022.05.18.

찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요

101일차 수업

tensorflow

import tensorflow as tf

# 상수 설정
a = tf.constant(1234)
b = tf.constant(5000)

# 텐서플로우의 세션 시작
@tf.function
def add_op():
    return a +  b

res = add_op()
# output tf.Tensor(6234, shape=(), dtype=int32)
res1 = res.numpy()	# output 6234

V1 사용하기

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()

# 상수 정의
a = tf.constant(120, name= a)
b = tf.constant(120, name= b)
c = tf.constant(120, name= c)

# 변수 정의
v = tf.Variable(0, name= v)

calc_op = a + b + c
assign_op = tf.assign(v, calc_op)

sess = tf.Session()
sess.run(assign_op)

print(sess.run(v))	# output 360

# placeholder 만들기
d = tf.placeholder(tf.int32, [3])
# 정수자료형 3개를 가진 배열, None으로 하면 배열의 크기 자유롭게 작성 가능
e = tf.constant(2)

x2_op = a * b

sess = tf.Session()

r1 = sess.run(x2_op, feed_dict={a:[1,2,3]})
print(r1)	# output 2 4 6

bmi 학습하기

import pandas as pd
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_eager_execution()

# 키, 몸무게, 레이블이 적힌 CSV 파일 읽어 들이기
csv = pd.read_csv("../day100/bmi.csv")

# 데이터 정규화
csv['height'] /= 200
csv['weight'] /= 100

# 레이블을 배열로 변환하기
# thin=(1,0,0) / normal=(0,1,0) / fat=(0,0,1)
bclass = {"thin": [1, 0, 0], "normal": [0, 1, 0], "fat": [0, 0, 1]}
csv["label_pat"] = csv["label"].apply(lambda x: np.array(bclass[x]))

# 테스트를 위한 데이터 분류
test_csv = csv[45000:50000]
test_pat = test_csv[["weight", "height"]]
test_ans = list(test_csv["label_pat"])

# 딥러닝을 위한 과정
# 학습데이터 : 배열 2칸 / 정답 데이터 : 배열 3칸 [0,0,0]
# 데이터 플로우 그래프 구축하기
# 플레이스홀더 선언하기
x = tf.placeholder(tf.float32, [None, 2])  # 키와 몸무게 데이터 넣기
y_ = tf.placeholder(tf.float32, [None, 3])  # 정답 레이블 넣기

# 변수 선언하기
W = tf.Variable(tf.zeros([2, 3]))  # 가중치
b = tf.Variable(tf.zeros([3]))  # 바이어스

# 소프트맥스 회귀 정의하기
y = tf.nn.softmax(tf.matmul(x, W) + b)

# 모델 훈련하기
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(cross_entropy)

# 정답률 구하기
predict = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(predict, tf.float32))

# 세션 시작하기
sess = tf.Session()
sess.run(tf.global_variables_initializer())  # 변수 초기화하기

# 학습 시키기
for step in range(3500):
    i = (step * 100) % 14000
    rows = csv[1 + i: 1 + i + 100]
    x_pat = rows[["weight", "height"]]
    y_ans = list(rows["label_pat"])
    fd = {x: x_pat, y_: y_ans}
    sess.run(train, feed_dict=fd)
    if step % 500 == 0:
        cre = sess.run(cross_entropy, feed_dict=fd)
        acc = sess.run(accuracy, feed_dict={x: test_pat, y_: test_ans})
        print("step=", step, "cre=", cre, "acc=", acc)

# 최종적인 정답률 구하기
acc = sess.run(accuracy, feed_dict={x: test_pat, y_: test_ans})
print("정답률 = ", acc)