TechTogetWorld

 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid

python 문법에 관한 글 입니다.

인공지능 tensor flow 코딩을 위해 python 문법에 대해 정리를 하고자 합니다.

글의 순서는 아래와 같습니다

==========================================

1. cheatsheet

 - python문법의 컨닝 페이퍼입니다.

2. 주제별 코딩예제 모음

3.  참고한 자료

==========================================

[cheatsheet]

cheatsheet.pdf

[주제별 코딩예제 모음]

auth.py

egoing.py

k8805.py

lib.py

python grammar.py

print('---수와 계산------------------------------------------------------------------------')
print(10 + 5)
print(10 - 5)
print(10 * 5)
print(10 / 5)

import math
print(math.ceil(2.2))
print(math.floor(2.7))
print(math.pow(2,10))
print(math.pi)

print('---문자와 데이터 타입----------------------------------------------------------------')
print('Hello')
print("Hello")
print("Hello 'world'")
print('Hello "world"')
print('Hello '+'world')
print('Hello '*3)
print('Hello'[0])
print('Hello'[1])
print('Hello'[2])

print('hello world'.capitalize())
print('hello world'.upper())
print('hello world'.__len__())
print(len('hello world'))
print('Hello world'.replace('world', 'programming'))

print("egoing's \"tutorial\"")
print("\\")
print("Hello\nworld")
print("Hello\t\tworld")
print("\a")
print('Hello\nworld')

print(10+5)
print("10"+"5")

print('---변수---------------------------------------------------------------------------')
x = 10
y = 5
print(x + y)

title = "python & ruby"
print("Title is " + title)

print('---문자열에서 변수의 사용---------------------------------------------------------------------------')
name = "이상효"
print("안녕하세요. "+name+"님")
print(name+"님을 위한 강의를 준비했습니다.")
print(name+"님 꼭 참석 부탁드립니다.")


print('---수계산 에서 변수의 사용---------------------------------------------------------------------------')
donation = 200
student = 10
sponsor = 100
print((donation*student)/sponsor)

print('---비교와 불리언---------------------------------------------------------------------------')
a=1
b=1
print(a==b)
print(1==2)
print(1>2)
print(1<2)
print(True)
print(False)

print('---조건문---------------------------------------------------------------------------')
if True:
print("code1")
print("code2")
print("code3")

print('---조건문의 활용---------------------------------------------------------------------------')
input = 11
real = 11
if real == input:
print("Hello!")

input = 11
real = 21
if real == input:
print("Hello!")
else:
print("Who are you?")

input = 33
real_egoing = 11
real_k8805 = "ab"
if real_egoing == input:
print("Hello!, egoing")
elif real_k8805 == input:
print("Hello!, k8805")
else:
print("Who are you?")

print('---입력과 출력---------------------------------------------------------------------------')
in_str = input("입력 해주세요.\n")
print(in_str.upper()+" World!")

print('---로그인 애플리케이션에 입력기능 추가하기-------------------------------------------------------------------------')
in_str = input("1 아이디를 입력해주세요.\n")
real_egoing = "11"
real_k8805 = "ab"
if real_egoing == in_str:
print("Hello!, egoing")
elif real_k8805 == in_str:
print("Hello!, k8805")
else:
print("Who are you?")

print('---논리 연산---------------------------------------------------------------------------')
in_str = input("2 아이디를 입력해주세요.\n")
real_egoing = "egoing"
real_k8805 = "k8805"
if real_egoing == in_str or real_k8805 == in_str:
print("Hello!")
else:
print("Who are you?")

input_id = input("아이디를 입력해주세요.\n")
input_pwd = input("비밀번호를 입력해주세요.\n")
real_id = "egoing"
real_pwd = "11"
if real_id == input_id:
if real_pwd == input_pwd:
print("Hello!")
else:
print("잘못된 비밀번호입니다")
else:
print("잘못된 아이디입니다")

input_id = input("아이디를 입력해주세요.\n")
input_pwd = input("비밀번호를 입력해주세요.\n")
real_id = "egoing"
real_pwd = "11"
if real_id == input_id and real_pwd == input_pwd:
print("Hello!")
else:
print("로그인에 실패했습니다")

print('---주석---------------------------------------------------------------------------')
'''
조건문 예제
egoing
2015
'''
# user input password
input = 33
real_egoing = 11
#real_k8805 = "ab"
if real_egoing == input:
print("Hello!, egoing")
#elif real_k8805 == input:
# print("Hello!, k8805")
else:
print("Who are you?")

print('---컨테이너---------------------------------------------------------------------------')
print(type('egoing')) # <class 'str'>
name = 'egoing'
print(name) # egoing
print(type(['egoing', 'leezche', 'graphittie'])) # <class 'list'>
names = ['egoing', 'leezche', 'graphittie']
print(names)
print(names[2]) # graphittie
egoing = ['programmer', 'seoul', 25, False]
egoing[1] = 'busan'
print(egoing) # ['programmer', 'busan', 25, False]

print('---사용설명서---------------------------------------------------------------------------')
al = ['A', 'B', 'C', 'D']
print(len(al)) # 4
al.append('E')
print(al) # ['A', 'B', 'C', 'D', 'E']
del (al[0])
print(al) # ['B', 'C', 'D', 'E']

print('---반복문---------------------------------------------------------------------------')
while False:
print('Hello world')
print('After while')

i = 0
while i < 3:
print('Hello world')
i = i + 1

i = 0
while i < 10:
print('print("Hello world ' + str(i * 9) + '")')
i = i + 1

i = 0
while i < 10:
if i == 4:
print(i)
i = i + 1

print('---컨테이너와 반복문-------------------------------------------------------------------------')
members = ['egoing', 'leezche', 'graphittie']
i = 0
while i < len(members):
print(members[i])
i = i + 1
members = ['egoing', 'leezche', 'graphittie']
for member in members:
print(member)
for item in range(5, 11):
print(item)
input_id = input("아이디를 입력해주세요.\n")
members = ['egoing', 'k8805', 'leezche']
for member in members:
if member == input_id:
print('Hello!, ' + member)
import sys
sys.exit()
print('Who are you?')

print('---함수---------------------------------------------------------------------------')
def a3():
print('aaa')
a3()
print('------------------------------------------------------------------------------------------')
def a3():
return 'aaa'
print(a3())
print('------------------------------------------------------------------------------------------')
def a(num):
return 'a' * num
print(a(3))
print('------------------------------------------------------------------------------------------')
input_id = input("아이디를 입력해주세요.\n")
def login(_id):
members = ['egoing', 'k8805', 'leezche']
for member in members:
if member == _id:
return True
return False
if login(input_id):
print('Hello, ' + input_id)
else:
print('Who are you?')
print('---모듈-------------------------------------------------------------------------------')
import math

print(math.ceil(2.9))
print(math.floor(2.9))
print(math.sqrt(16))

print('----모듈이 없을때-----------------------------------------------------------------------------------')
def a():
return 'B'
from egoing import a as z
import k8805 as k

print(z())
print(k.a())

print('---객체제작_객체사용---------------------------------------------------------------------------')
class Cal(object):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2

def add(self):
return self.v1 + self.v2

def subtract(self):
return self.v1 - self.v2
c1 = Cal(10, 10)
print(c1.add())
print(c1.subtract())
c2 = Cal(30, 20)
print(c2.add())
print(c2.subtract())

print('------객체제작_클래스-----------------------------------------------------------------')
class Cal(object):
c1 = Cal(10, 10)
print(c1.add())
print(c1.subtract())
c2 = Cal(30, 20)
print(c2.add())
print(c2.subtract())
print('------객체제작_생성자-----------------------------------------------------------------')
class Cal(object):
def __init__(self, v1, v2):
print(v1, v2)
c1 = Cal(10, 10)
# print(c1.add())
# print(c1.subtract())
c2 = Cal(30, 20)
# print(c2.add())
# print(c2.subtract())
print('------객체제작_인스턴스 변수와 메소드-----------------------------------------------------------------')
class Cal(object):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2

def add(self):
return self.v1 + self.v2

def subtract(self):
return self.v1 - self.v2
c1 = Cal(10, 10)
print(c1.add())
print(c1.subtract())
c2 = Cal(30, 20)
print(c2.add())
print(c2.subtract())
print('------객체와변수_인스턴스 변수의 특성-----------------------------------------------------------------')
class C(object):
def __init__(self, v):
self.value = v

def show(self):
print(self.value)
c1 = C(10)
print(c1.value)
c1.value = 20
print(c1.value)
c1.show()
print('------객체와변수_set/get 메소드--------------------------------------------------------------')
class C(object):
def __init__(self, v):
self.value = v

def show(self):
print(self.value)

def getValue(self):
return self.value

def setValue(self, v):
self.value = v
c1 = C(10)
print(c1.getValue())
c1.setValue(20)
print(c1.getValue())
print('------객체와변수_set/get 메소드를 사용해야하는 이유--------------------------------------------------')
class Cal(object):
def __init__(self, v1, v2):
if isinstance(v1, int):
self.v1 = v1
if isinstance(v2, int):
self.v2 = v2

def add(self):
return self.v1 + self.v2

def subtract(self):
return self.v1 - self.v2

def setV1(self, v):
if isinstance(v, int): # v 가 int class의 인스턴스인지 확인
self.v1 = v

def getV1(self):
return self.v1
c1 = Cal(10, 10)
print(c1.add())
print(c1.subtract())
c1.setV1('one')
c1.v2 = 30
print(c1.add())
print(c1.subtract())

print('---------객체와변수_속성 : 실행않됨---------------------------------------------------------------------')
"""
class C(object):
def __init__(self, v):
self.__value = v
def show(self):
print(self.__value)
c1 = C(10)
print(c1.__value)
c1.show()

"""
print('---상속_상속의 문법---------------------------------------------------------------------------')
class Class1(object):
def method1(self): return 'm1'
c1 = Class1()
print(c1, c1.method1())
class Class3(Class1):
def method2(self): return 'm2'
c3 = Class3()
print(c3, c3.method1())
print(c3, c3.method2())

class Class2(object):
def method1(self): return 'm1'
def method2(self): return 'm2'
c2 = Class2()
print(c2, c2.method1())
print(c2, c2.method2())

print('-----상속_상속의 응용-------------------------------------------------------------------')
"""
클래스의 재활용/함수추가 : 타인의 또는 자신의 클래스를 상속하고, 새로운 기능추가, 상속은 변수까지도 이어받음
"""
class Cal(object):
def __init__(self, v1, v2):
if isinstance(v1, int):
self.v1 = v1
if isinstance(v2, int):
self.v2 = v2

def add(self):
return self.v1 + self.v2

def subtract(self):
return self.v1 - self.v2

def setV1(self, v):
if isinstance(v, int):
self.v1 = v

def getV1(self):
return self.v1


class CalMultiply(Cal):
def multiply(self):
return self.v1 * self.v2


class CalDivide(CalMultiply):
def divide(self):
return self.v1 / self.v2


c1 = CalMultiply(10, 10)
print(c1.add())
print(c1.multiply())
c2 = CalDivide(20, 10)
print(c2, c2.add())
print(c2, c2.multiply())
print(c2, c2.divide())

print('-------------clss멤버_클래스 매소드--------------------------------------------------------------')
class Cs:
@staticmethod
def static_method():
print("Static method")

@classmethod
def class_method(cls):
print("Class method")

def instance_method(self):
print("Instance method")

i = Cs()
Cs.static_method()
Cs.class_method()
i.instance_method()

print('-------------clss멤버_클래스 변수---------------------------------------------------------------')
class Cs:
count = 0

def __init__(self):
Cs.count = Cs.count + 1

@classmethod
def getCount(cls):
return Cs.count
i1 = Cs()
i2 = Cs()
i3 = Cs()
i4 = Cs()
print(Cs.getCount())

print('-------------clss멤버_clss member의 활용---------------------------------------------------------------')
class Cal(object):
_history = []

def __init__(self, v1, v2):
if isinstance(v1, int):
self.v1 = v1
if isinstance(v2, int):
self.v2 = v2

def add(self):
result = self.v1 + self.v2
Cal._history.append("add : %d+%d=%d" % (self.v1, self.v2, result))
return result

def subtract(self):
result = self.v1 - self.v2
Cal._history.append("subtract : %d-%d=%d" % (self.v1, self.v2, result))
return result

def setV1(self, v):
if isinstance(v, int):
self.v1 = v

def getV1(self):
return self.v1

@classmethod
def history(cls):
for item in Cal._history:
print(item)
class CalMultiply(Cal):
def multiply(self):
result = self.v1 * self.v2
Cal._history.append("multiply : %d*%d=%d" % (self.v1, self.v2, result))
return result
class CalDivide(CalMultiply):
def divide(self):
result = self.v1 / self.v2
Cal._history.append("divide : %d/%d=%d" % (self.v1, self.v2, result))
return result
c1 = CalMultiply(10, 10)
print(c1.add())
print(c1.multiply())
c2 = CalDivide(20, 10)
print(c2, c2.add())
print(c2, c2.multiply())
print(c2, c2.divide())
Cal.history()
print('-------------override_형식---------------------------------------------------------------')
class C1:
def m(self):
return 'parent'
class C2(C1):
def m(self):
return super().m() + ' child'
pass
o = C2()
print(o.m())

print('-------------override_override 활용---------------------------------------------------------------')
class Cal(object):
_history = []

def __init__(self, v1, v2):
if isinstance(v1, int):
self.v1 = v1
if isinstance(v2, int):
self.v2 = v2

def add(self):
result = self.v1 + self.v2
Cal._history.append("add : %d+%d=%d" % (self.v1, self.v2, result))
return result

def subtract(self):
result = self.v1 - self.v2
Cal._history.append("subtract : %d-%d=%d" % (self.v1, self.v2, result))
return result

def setV1(self, v):
if isinstance(v, int):
self.v1 = v

def getV1(self):
return self.v1

@classmethod
def history(cls):
for item in Cal._history:
print(item)

def info(self):
return "Cal => v1 : %d, v2 : %d" % (self.v1, self.v2)
class CalMultiply(Cal):
def multiply(self):
result = self.v1 * self.v2
Cal._history.append("multiply : %d*%d=%d" % (self.v1, self.v2, result))
return result

def info(self):
return "CalMultiply => %s" % super().info()
class CalDivide(CalMultiply):
def divide(self):
result = self.v1 / self.v2
Cal._history.append("divide : %d/%d=%d" % (self.v1, self.v2, result))
return result

def info(self):
return "CalDivide => %s" % super().info()
c0 = Cal(30, 60)
print(c0.info())
c1 = CalMultiply(10, 10)
print(c1.info())
c2 = CalDivide(20, 10)
print(c2.info())

print('-------------객체와 모듈---------------------------------------------------------------')
import lib
obj = lib.A()
print(obj.a())

print('-------------다중상속_형식,단점---------------------------------------------------------------')
class C1():
def c1_m(self):
print("c1_m")

def m(self):
print("C1 m")
class C2():
def c2_m(self):
print("c2_m")
def m(self):
print("C2 m")

class C3(C2, C1):
def m(self):
print("C3 m")
c = C3()
c.c1_m()
c.c2_m()
c.m()
print(C3.__mro__)

print('-------------다중상속_다중상속의 활용---------------------------------------------------------------')
class CalMultiply():
def multiply(self):
return self.v1 * self.v2
class CalDivide():
def divide(self):
return self.v1 / self.v2
class Cal(CalMultiply, CalDivide): # 왼쪽부모가 우선순위가 높다
def __init__(self, v1, v2):
if isinstance(v1, int):
self.v1 = v1
if isinstance(v2, int):
self.v2 = v2
def add(self):
return self.v1 + self.v2

def subtract(self):
return self.v1 - self.v2
def setV1(self, v):
if isinstance(v, int):
self.v1 = v
def getV1(self):
return self.v1
c = Cal(100, 10)
print(c.add())
print(c.multiply())

print(c.divide())



[참고한 자료]


https://opentutorials.org/course/1750    생활코딩 

 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid

인공지능 구현에 대한 글입니다.
글의 순서는 아래와 같습니다.

================================================
1. multinomial  적용
  ==>합격/불합격이 아닌, A,B,C,D,를 예측하는 개념임
2. Fancy softmax classfication 구현
  ==> 동물들(레이블, 클래스)를 여러특징들(x)로 예측함.
3. Next step
  ==> Multinomial  : 여러개의 classification의 확율을 구함.
4. 참고자료
=================================================

multinomial  적용]


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# Lab 6 Softmax Classifier

import tensorflow as tf

tf.set_random_seed(777)  # for reproducibility


x_data = [[1, 2, 1, 1],

          [2, 1, 3, 2],

          [3, 1, 3, 4],

          [4, 1, 5, 5],

          [1, 7, 5, 5],

          [1, 2, 5, 6],

          [1, 6, 6, 6],

          [1, 7, 7, 7]]

y_data = [[0, 0, 1], ==>2

          [0, 0, 1], ==>2

          [0, 0, 1],

          [0, 1, 0], ==>1

          [0, 1, 0],

          [0, 1, 0],

          [1, 0, 0],

          [1, 0, 0]]


X = tf.placeholder("float", [None, 4])

Y = tf.placeholder("float", [None, 3])

nb_classes = 3


W = tf.Variable(tf.random_normal([4, nb_classes]), name='weight')

b = tf.Variable(tf.random_normal([nb_classes]), name='bias')


# tf.nn.softmax computes softmax activations


==> 확율( 1~0 )으로 변환해줌

# softmax = exp(logits) / reduce_sum(exp(logits), dim)

hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)




# Cross entropy cost/loss 

cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))


D(S,L)=-SIGMA Li log(Si) 함수와   

는 같은 결과를 나타냄


예측이 맞으면  COST는  작아지고, 틀리면 커지도록 구성한 함수임.

상기 함수(상기 2함수는 같은결과를 내고있음 , 같은 함수라고 할수있음)가 그 역할을 충실히 해내고 있음.


optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)

COST 최소화 실행


# Launch graph

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())


    for step in range(2001):

        sess.run(optimizer, feed_dict={X: x_data, Y: y_data})

        if step % 200 == 0:

            print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}))


    print('--------------')


    # Testing & One-hot encoding

    a = sess.run(hypothesis, feed_dict={X: [[1, 11, 7, 9]]})

    print(a, sess.run(tf.arg_max(a, 1)))

    ==> 예측치 출력(3개) , one hot 값 출력 ==> 어떤 클래스 인지를 결정해서 출력해줌

    ==> 예시)손글씨의 특징을 3개의 x 값으로 표현하고, 예측치를 출력 3개로 하며, 이때 확율이 가장높게나타난 클래스가  해당 손글씨가 됨.

    ==> 예시) 글래스(강아지,고양이...)등의 특징을 여러 x갋으로 표현하고, 예측을 y값으로 예측하고, 그중 확율이 제일 높은수치를 선택해줌, 제일 큰 수치가 해당클래스(고양이, 강아지 등)가 된다.


    print('--------------')


    b = sess.run(hypothesis, feed_dict={X: [[1, 3, 4, 3]]})

    print(b, sess.run(tf.arg_max(b, 1)))


    print('--------------')


    c = sess.run(hypothesis, feed_dict={X: [[1, 1, 0, 1]]})

    print(c, sess.run(tf.arg_max(c, 1)))


    print('--------------')


    all = sess.run(hypothesis, feed_dict={

                   X: [[1, 11, 7, 9], [1, 3, 4, 3], [1, 1, 0, 1]]})

    print(all, sess.run(tf.arg_max(all, 1)))


'''

--------------

[[  1.38904958e-03   9.98601854e-01   9.06129117e-06]] [1]  ==> 전체의 합은 1 임

--------------

[[ 0.93119204  0.06290206  0.0059059 ]] [0]

--------------

[[  1.27327668e-08   3.34112905e-04   9.99665856e-01]] [2]

--------------

[[  1.38904958e-03   9.98601854e-01   9.06129117e-06]

 [  9.31192040e-01   6.29020557e-02   5.90589503e-03]

 [  1.27327668e-08   3.34112905e-04   9.99665856e-01]] [1 0 2]

'''



[ Fancy softmax classfication 구현 ]

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# Lab 6 Softmax Classifier

import tensorflow as tf

import numpy as np

tf.set_random_seed(777)  # for reproducibility


# Predicting animal type based on various features

xy = np.loadtxt('data-04-zoo.csv', delimiter=',', dtype=np.float32)

x_data = xy[:, 0:-1]

y_data = xy[:, [-1]]


print(x_data.shape, y_data.shape)


nb_classes = 7  # 0 ~ 6


X = tf.placeholder(tf.float32, [None, 16])

Y = tf.placeholder(tf.int32, [None, 1])  # 0 ~ 6

Y_one_hot = tf.one_hot(Y, nb_classes)  # one hot

print("one_hot", Y_one_hot)

Y_one_hot = tf.reshape(Y_one_hot, [-1, nb_classes])

# one hot을 하면 rank가 1개 늘어나게 된다, 이를 다시 줄이는 역할을 하는것이 reshape 임 

print("reshape", Y_one_hot)


W = tf.Variable(tf.random_normal([16, nb_classes]), name='weight')

b = tf.Variable(tf.random_normal([nb_classes]), name='bias')


# tf.nn.softmax computes softmax activations

# softmax = exp(logits) / reduce_sum(exp(logits), dim)

logits = tf.matmul(X, W) + b

hypothesis = tf.nn.softmax(logits)


# Cross entropy cost/loss

cost_i = tf.nn.softmax_cross_entropy_with_logits(logits=logits,

                                                 labels=Y_one_hot)

cost = tf.reduce_mean(cost_i)

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)


prediction = tf.argmax(hypothesis, 1)

correct_prediction = tf.equal(prediction, tf.argmax(Y_one_hot, 1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Launch graph

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())


    for step in range(2000):

        sess.run(optimizer, feed_dict={X: x_data, Y: y_data})

        if step % 100 == 0:

            loss, acc = sess.run([cost, accuracy], feed_dict={

                                 X: x_data, Y: y_data})

            print("Step: {:5}\tLoss: {:.3f}\tAcc: {:.2%}".format(

                step, loss, acc))


    # Let's see if we can predict

    pred = sess.run(prediction, feed_dict={X: x_data})

    # y_data: (N,1) = flatten => (N, ) matches pred.shape

    for p, y in zip(pred, y_data.flatten()):

        print("[{}] Prediction: {} True Y: {}".format(p == int(y), p, int(y)))


'''

Step:     0 Loss: 5.106 Acc: 37.62%

Step:   100 Loss: 0.800 Acc: 79.21%

Step:   200 Loss: 0.486 Acc: 88.12%

Step:   300 Loss: 0.349 Acc: 90.10%

Step:   400 Loss: 0.272 Acc: 94.06%

Step:   500 Loss: 0.222 Acc: 95.05%

Step:   600 Loss: 0.187 Acc: 97.03%

Step:   700 Loss: 0.161 Acc: 97.03%

Step:   800 Loss: 0.140 Acc: 97.03%

Step:   900 Loss: 0.124 Acc: 97.03%

Step:  1000 Loss: 0.111 Acc: 97.03%

Step:  1100 Loss: 0.101 Acc: 99.01%

Step:  1200 Loss: 0.092 Acc: 100.00%



[참고자료 ]

https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/ 

http://agiantmind.tistory.com/176 

https://www.tensorflow.org/install/

https://github.com/hunkim/deeplearningzerotoall

http://www.derivative-calculator.net/

http://terms.naver.com/entry.nhn?docId=3350391&cid=58247&categoryId=58247    ==> 미분계산/공식

http://matplotlib.org/users/installing.html   ==>matplotlib 설치

https://www.kaggle.com/==> DATA SAMPLE 을 구할수 있는 사이트



 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid

python 문법에 관한 글 입니다.

인공지능 tensor flow 코딩을 위해 python 문법에 대해 정리를 하고자 합니다.

글의 순서는 아래와 같습니다

==========================================

1.Logistics classification 가설함수

  ==> 합격, 불합격을 구분할때 적용함

2. 당뇨병 예측

3. Next step

  ==> Multinomial  : 여러개의 classification의 확율을 구함.

4. 참고자료 

============================================


Logistics classification 가설함수]



import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'


# Lab 5 Logistic Regression Classifier

import tensorflow as tf

tf.set_random_seed(777)  # for reproducibility


x_data = [[1, 2],

          [2, 3],

          [3, 1],

          [4, 3],

          [5, 3],

          [6, 2]]


x data에 따라 합부(0,1)로 나타는 Y data를 예측함

# 공부한 시간에 따른 합격여부 data


y_data = [[0],

          [0],

          [0],

          [1],

          [1],

          [1]]


# placeholders for a tensor that will be always fed.

X = tf.placeholder(tf.float32, shape=[None, 2])

Y = tf.placeholder(tf.float32, shape=[None, 1])


W = tf.Variable(tf.random_normal([2, 1]), name='weight')

b = tf.Variable(tf.random_normal([1]), name='bias')



sigmoid 함수 사용함


 ==> h(x) 가 0~1 사이에 값을 갖게됨.




==> cost(w)은  y값과 h(x)차이가 크면 1에 가깝고, 작으면 0에 가까워지도록 구현함 , 이를 하나의 공식으로 통일시킴.

  -기존의 cost함수형식으로 하게되면  울퉁불퉁한 2차 곡선 형태되고, 경사를 내려오면서 수많은 기울기 0 지점을 지나게 되어, 목표지점에 다다르지 못하게됨

  -따라서 다른 코스트 함수가 필요함, 아래 함수가 그 대안임




# Hypothesis using sigmoid: tf.div(1., 1. + tf.exp(tf.matmul(X, W)))

hypothesis = tf.sigmoid(tf.matmul(X, W) + b)


# cost/loss function

cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) *

                       tf.log(1 - hypothesis))


train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)


# Accuracy computation

# True if hypothesis>0.5 else False

predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)

accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))


# Launch graph

with tf.Session() as sess:

    # Initialize TensorFlow variables

    sess.run(tf.global_variables_initializer())


    for step in range(10001):

        cost_val, _ = sess.run([cost, train], feed_dict={X: x_data, Y: y_data})

        if step % 200 == 0:

            print(step, cost_val)


    # Accuracy report

    h, c, a = sess.run([hypothesis, predicted, accuracy],

                       feed_dict={X: x_data, Y: y_data})

    print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a)


'''

0 1.73078

200 0.571512

400 0.507414

600 0.471824

800 0.447585

...

9200 0.159066

9400 0.15656

9600 0.154132

9800 0.151778

10000 0.149496


Hypothesis:  [[ 0.03074029]

 [ 0.15884677]

 [ 0.30486736]

 [ 0.78138196]

 [ 0.93957496]

 [ 0.98016882]]

y 예측치


Correct (Y):  [[ 0.]

 [ 0.]

 [ 0.]

 [ 1.]

 [ 1.]

 [ 1.]]

y 예측치와 실제 y값의 차가 0.5 이상이면 0.  이하면 1 

Accuracy:  1.0

예측정확도 100%

'''


'''


[당뇨병 예측]


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# Lab 5 Logistic Regression Classifier

import tensorflow as tf

import numpy as np

tf.set_random_seed(777)  # for reproducibility


xy = np.loadtxt('data-03-diabetes.csv', delimiter=',', dtype=np.float32)

x_data = xy[:, 0:-1]

y_data = xy[:, [-1]]


print(x_data.shape, y_data.shape)


# placeholders for a tensor that will be always fed.

X = tf.placeholder(tf.float32, shape=[None, 8])

Y = tf.placeholder(tf.float32, shape=[None, 1])


W = tf.Variable(tf.random_normal([8, 1]), name='weight')

b = tf.Variable(tf.random_normal([1]), name='bias')


# Hypothesis using sigmoid: tf.div(1., 1. + tf.exp(tf.matmul(X, W)))

hypothesis = tf.sigmoid(tf.matmul(X, W) + b)


# cost/loss function

cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) *

                       tf.log(1 - hypothesis))


train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)


# Accuracy computation

# True if hypothesis>0.5 else False

predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)

accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))


# Launch graph

with tf.Session() as sess:

    # Initialize TensorFlow variables

    sess.run(tf.global_variables_initializer())


    for step in range(10001):

        cost_val, _ = sess.run([cost, train], feed_dict={X: x_data, Y: y_data})

        if step % 200 == 0:

            print(step, cost_val)


    # Accuracy report

    h, c, a = sess.run([hypothesis, predicted, accuracy],

                       feed_dict={X: x_data, Y: y_data})

    print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a)


'''

0 0.82794

200 0.755181

400 0.726355

600 0.705179

800 0.686631

...

9600 0.492056

9800 0.491396

10000 0.490767


...


 [ 1.]

 [ 1.]

 [ 1.]]

Accuracy:  0.762846




[ 참고자료 ]


https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/ 

http://agiantmind.tistory.com/176 

https://www.tensorflow.org/install/

https://github.com/hunkim/deeplearningzerotoall

http://www.derivative-calculator.net/

http://terms.naver.com/entry.nhn?docId=3350391&cid=58247&categoryId=58247    ==> 미분계산/공식

http://matplotlib.org/users/installing.html   ==>matplotlib 설치

https://www.kaggle.com/==> DATA SAMPLE 을 구할수 있는 사이트

'''





 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid



인공지능 구현에 대한 글입니다.

글의 순서는 아래와 같습니다.


================================================

1. X의 갯수가3개인 경우

  ==> 코딩이 매우 복잡해짐 , 대안으로 "매트릭스_행렬 "을 사용하면 간단해짐.

2. 매트릭스 적용

  ==> DATA 갯수(X 변수의갯수) 이 많아져도 간단하게 코딩이 가능해짐

3. TENSOR FLOW로 파일에서 DATA 읽어오기

  ==> DATA를  프로그램상에 올리면 메모리한계가 있으므로, DATA를 별도의 화일에 저장하고 불러오는것이 유리함

4. DATA QUE로 읽어들임 시간차로 처리해서 시스템 부하를 줄어줌

 ==> 화일이 많거나, 용량이 커지면  TENSORFLOW에서 자동으로 시간차를 두고 처리해주는 시스템 구현이 가능함

5. Next step

  ==> LOGISTICS 알고리즘 : CLASSSIFICATION 중 주요한 알고리즘.

6.참고자료 


=================================================



[ Cost 최소화 알고리즘 구현 소스코드 분석 ]


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# Lab 4 Multi-variable linear regression

import tensorflow as tf

tf.set_random_seed(777)  # for reproducibility

==> x값이 3개

x1_data = [73., 93., 89., 96., 73.]

x2_data = [80., 88., 91., 98., 66.]

x3_data = [75., 93., 90., 100., 70.]


y_data = [152., 185., 180., 196., 142.]


# placeholders for a tensor that will be always fed.

x1 = tf.placeholder(tf.float32)

x2 = tf.placeholder(tf.float32)

x3 = tf.placeholder(tf.float32)


Y = tf.placeholder(tf.float32)


w1 = tf.Variable(tf.random_normal([1]), name='weight1')

w2 = tf.Variable(tf.random_normal([1]), name='weight2')

w3 = tf.Variable(tf.random_normal([1]), name='weight3')

b = tf.Variable(tf.random_normal([1]), name='bias')


hypothesis = x1 * w1 + x2 * w2 + x3 * w3 + b

print(hypothesis)

==> x,w값이 3개(x1,x2,x3 ,w1,w2,w3) 인 가설임

==> 코딩이 매우 복잡해짐 , 대안으로 "매트릭스_행렬 "을 사용하면 간단해짐.

# cost/loss function

cost = tf.reduce_mean(tf.square(hypothesis - Y))


# Minimize. Need a very small learning rate for this data set

optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)

train = optimizer.minimize(cost)


# Launch the graph in a session.

sess = tf.Session()

# Initializes global variables in the graph.

sess.run(tf.global_variables_initializer())


for step in range(2001):

    cost_val, hy_val, _ = sess.run([cost, hypothesis, train],

                                   feed_dict={x1: x1_data, x2: x2_data, x3: x3_data, Y: y_data})

    if step % 10 == 0:

        print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)


'''

0 Cost:  19614.8

Prediction:

 [ 21.69748688  39.10213089  31.82624626  35.14236832  32.55316544]

10 Cost:  14.0682

Prediction:

 [ 145.56100464  187.94958496  178.50236511  194.86721802  146.08096313]


 ...


1990 Cost:  4.9197

Prediction:

 [ 148.15084839  186.88632202  179.6293335   195.81796265  144.46044922]

2000 Cost:  4.89449

Prediction:

 [ 148.15931702  186.8805542   179.63194275  195.81971741  144.45298767]

'''


[ 매트릭스 적용 ]


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# Lab 4 Multi-variable linear regression

import tensorflow as tf

tf.set_random_seed(777)  # for reproducibility



매트릭로 DATA 적용


x_data = [[73., 80., 75.],

          [93., 88., 93.],

          [89., 91., 90.],

          [96., 98., 100.],

          [73., 66., 70.]]

y_data = [[152.],

          [185.],

          [180.],

          [196.],

          [142.]]


# placeholders for a tensor that will be always fed.

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

Y = tf.placeholder(tf.float32, shape=[None, 1])


W = tf.Variable(tf.random_normal([3, 1]), name='weight')

b = tf.Variable(tf.random_normal([1]), name='bias')


매트릭스 곱샘 코딩

# Hypothesis

hypothesis = tf.matmul(X, W) + b




# Simplified cost/loss function

cost = tf.reduce_mean(tf.square(hypothesis - Y))


# Minimize

optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)

train = optimizer.minimize(cost)


# Launch the graph in a session.

sess = tf.Session()

# Initializes global variables in the graph.

sess.run(tf.global_variables_initializer())


for step in range(2001):

    cost_val, hy_val, _ = sess.run(

        [cost, hypothesis, train], feed_dict={X: x_data, Y: y_data})

    if step % 10 == 0:

        print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)


'''

0 Cost:  7105.46

Prediction:

 [[ 80.82241058]

 [ 92.26364136]

 [ 93.70250702]

 [ 98.09217834]

 [ 72.51759338]]

10 Cost:  5.89726

Prediction:

 [[ 155.35159302]

 [ 181.85691833]

 [ 181.97254944]

 [ 194.21760559]

 [ 140.85707092]]


...


1990 Cost:  3.18588

Prediction:

 [[ 154.36352539]

 [ 182.94833374]

 [ 181.85189819]

 [ 194.35585022]

 [ 142.03240967]]

2000 Cost:  3.1781

Prediction:

 [[ 154.35881042]

 [ 182.95147705]

 [ 181.85035706]

 [ 194.35533142]

 [ 142.036026  ]]


'''



TENSOR FLOW로 파일에서 DATA 읽어오기 ]


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# Lab 4 Multi-variable linear regression

import tensorflow as tf

import numpy as np

tf.set_random_seed(777)  # for reproducibility


DATA는 CSV 화일에 저장됨, CSV 화일 위치는 PY 화일위치에 있음

xy = np.loadtxt('data-01-test-score.csv', delimiter=',', dtype=np.float32)


슬라이싱방법 숙지필요함

x_data = xy[:, 0:-1]

y_data = xy[:, [-1]]


# Make sure the shape and data are OK

print(x_data.shape, x_data, len(x_data))

print(y_data.shape, y_data)


# placeholders for a tensor that will be always fed.

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

Y = tf.placeholder(tf.float32, shape=[None, 1])


W = tf.Variable(tf.random_normal([3, 1]), name='weight')

b = tf.Variable(tf.random_normal([1]), name='bias')


# Hypothesis

hypothesis = tf.matmul(X, W) + b


# Simplified cost/loss function

cost = tf.reduce_mean(tf.square(hypothesis - Y))


# Minimize

optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)

train = optimizer.minimize(cost)


# Launch the graph in a session.

sess = tf.Session()

# Initializes global variables in the graph.

sess.run(tf.global_variables_initializer())


for step in range(2001):

    cost_val, hy_val, _ = sess.run(

        [cost, hypothesis, train], feed_dict={X: x_data, Y: y_data})

    if step % 10 == 0:

        print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)


나의 점수 예측

# Ask my score

print("Your score will be ", sess.run(

    hypothesis, feed_dict={X: [[100, 70, 101]]}))




print("Other scores will be ", sess.run(hypothesis,

                                        feed_dict={X: [[60, 70, 110], [90, 100, 80]]}))


'''


타인의 점수 예측

Your score will be  [[ 181.73277283]]

Other scores will be  [[ 145.86265564]

 [ 187.23129272]]


'''


DATA QUE로 읽어들임 시간차로 처리해서 시스템 부하를 줄어줌 ]



import tensorflow as tf

tf.set_random_seed(777)  # for reproducibility


화일 하나를 위한 QUE를 만듦

filename_queue = tf.train.string_input_producer(

    ['data-01-test-score.csv'], shuffle=False, name='filename_queue')


화일 리더 정의

reader = tf.TextLineReader()

key, value = reader.read(filename_queue)


# Default values, in case of empty columns. Also specifies the type of the

# decoded result.


CSV로 디코딩

record_defaults = [[0.], [0.], [0.], [0.]]

xy = tf.decode_csv(value, record_defaults=record_defaults)



불러올때마다 10 개씩 불러옴 (BATCH_SIZE =10 )

# collect batches of csv in

train_x_batch, train_y_batch = \

    tf.train.batch([xy[0:-1], xy[-1:]], batch_size=10)


# placeholders for a tensor that will be always fed.


X 3개 , Y 1개 데이터 숫자를 맞추어줌


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

Y = tf.placeholder(tf.float32, shape=[None, 1])


W = tf.Variable(tf.random_normal([3, 1]), name='weight')

b = tf.Variable(tf.random_normal([1]), name='bias')


# Hypothesis

hypothesis = tf.matmul(X, W) + b


# Simplified cost/loss function

cost = tf.reduce_mean(tf.square(hypothesis - Y))


# Minimize

optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)

train = optimizer.minimize(cost)


# Launch the graph in a session.

sess = tf.Session()

# Initializes global variables in the graph.

sess.run(tf.global_variables_initializer())


# Start populating the filename queue.

coord = tf.train.Coordinator()

threads = tf.train.start_queue_runners(sess=sess, coord=coord)


for step in range(2001):


x_batch , y_batch 값을  train feed_dict로 넘겨줌

    x_batch, y_batch = sess.run([train_x_batch, train_y_batch])

    cost_val, hy_val, _ = sess.run(

        [cost, hypothesis, train], feed_dict={X: x_batch, Y: y_batch})

    if step % 10 == 0:

        print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)


coord.request_stop()

coord.join(threads)


# Ask my score

print("Your score will be ",

      sess.run(hypothesis, feed_dict={X: [[100, 70, 101]]}))


print("Other scores will be ",

      sess.run(hypothesis, feed_dict={X: [[60, 70, 110], [90, 100, 80]]}))


'''

Your score will be  [[ 177.78144836]]

Other scores will be  [[ 141.10997009]

 [ 191.17378235]]


'''




[참고자료 ]


https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/

http://agiantmind.tistory.com/176 

https://www.tensorflow.org/install/

https://github.com/hunkim/deeplearningzerotoall

http://www.derivative-calculator.net/

http://terms.naver.com/entry.nhn?docId=3350391&cid=58247&categoryId=58247    ==> 미분계산/공식

http://matplotlib.org/users/installing.html   ==>matplotlib 설치




 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid



인공지능 구현에 대한 글입니다.

글의 순서는 아래와 같습니다.


================================================

1. Cost 최소화 알고리즘 구현 소스코드 분석

2. Cost Minimize 코딩 작성 ( cost 를 미분해서 W변화량 적용)

3. Optimizer 적용 테스트

 - 간단한 미분은 상기과 같이 직접코딩이 가능하겠으나, 복잡해지면 통상적으로 optimizer로 코딩함

4. Optimizer 적용 과 수작업(미분계산) 수치 비교

 - 경사도 수치를 중간에 변형할수 있도록 코딩함 (gvs) ==> 거의 같음

5. Next step

  ==> multivariable linear regresstion : 하나이상의 변수적용

6. 참고자료

=================================================


[ Cost 최소화 알고리즘 구현 소스코드 분석 ]


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'


# Lab 3 Minimizing Cost

import tensorflow as tf

import matplotlib.pyplot as plt

==> matplotlib를 사용키 위해서는 별도로 설치를 해야함

==> http://matplotlib.org/users/installing.html

==> 그래프를 그려주는 기능임.


tf.set_random_seed(777)  # for reproducibility


X = [1, 2, 3]

Y = [1, 2, 3]


W = tf.placeholder(tf.float32)


# Our hypothesis for linear model X * W

hypothesis = X * W


# cost/loss function

cost = tf.reduce_mean(tf.square(hypothesis - Y))


# Launch the graph in a session.

sess = tf.Session()


# Variables for plotting cost function

W_history = []

cost_history = []

==> 그래프를 그리기 위해 배열할당


for i in range(-30, 50):

    curr_W = i * 0.1

    curr_cost = sess.run(cost, feed_dict={W: curr_W})

    W_history.append(curr_W)

    cost_history.append(curr_cost)

# Show the cost function

plt.plot(W_history, cost_history)

plt.show()



Cost Minimize 코딩 작성 ( cost 를 미분해서 W변화량 적용) ]


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'


# Lab 3 Minimizing Cost

import tensorflow as tf

tf.set_random_seed(777)  # for reproducibility


x_data = [1, 2, 3]

y_data = [1, 2, 3]


# Try to find values for W and b to compute y_data = W * x_data + b

# We know that W should be 1 and b should be 0

# But let's use TensorFlow to figure it out

W = tf.Variable(tf.random_normal([1]), name='weight')


X = tf.placeholder(tf.float32)

Y = tf.placeholder(tf.float32)


# Our hypothesis for linear model X * W

hypothesis = X * W


# cost/loss function

cost = tf.reduce_mean(tf.square(hypothesis - Y))




W값의  descent 간격을 구하는 과정을 미분방정식으로 직접(수작업) 코딩하는 내용입니다( 아래그림은 미분적용 과정입니다)


 



# Minimize: Gradient Descent using derivative: W -= learning_rate * derivative

learning_rate = 0.1

gradient = tf.reduce_mean((W * X - Y) * X)

descent = W - learning_rate * gradient

update = W.assign(descent)


간단한 미분은 상기과 같이 직접코딩이 가능하겠으나, 복잡해지면 통상적으로 아래와 같이 코딩을 하는것이 일반적임(텐서플로우가 자동계산을 해줌)


# Launch the graph in a session.

sess = tf.Session()

# Initializes global variables in the graph.

sess.run(tf.global_variables_initializer())


for step in range(21):

    sess.run(update, feed_dict={X: x_data, Y: y_data})

    print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W))


'''

0 1.93919 [ 1.64462376]

1 0.551591 [ 1.34379935]

2 0.156897 [ 1.18335962]

3 0.0446285 [ 1.09779179]

4 0.0126943 [ 1.05215561]

5 0.00361082 [ 1.0278163]

6 0.00102708 [ 1.01483536]

7 0.000292144 [ 1.00791216]

8 8.30968e-05 [ 1.00421977]

9 2.36361e-05 [ 1.00225055]

10 6.72385e-06 [ 1.00120032]

11 1.91239e-06 [ 1.00064015]

12 5.43968e-07 [ 1.00034142]

13 1.54591e-07 [ 1.00018203]

14 4.39416e-08 [ 1.00009704]

15 1.24913e-08 [ 1.00005174]

16 3.5322e-09 [ 1.00002754]

17 9.99824e-10 [ 1.00001466]

18 2.88878e-10 [ 1.00000787]

19 8.02487e-11 [ 1.00000417]

20 2.34053e-11 [ 1.00000226]

'''


[ Optimizer 적용 테스트 ]

import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Lab 3 Minimizing Cost import tensorflow as tf tf.set_random_seed(777) # for reproducibility # tf Graph Input X = [1, 2, 3] Y = [1, 2, 3] # Set wrong model weights W = tf.Variable(5.0) ==> w 값을 터무니없는 값을 주고, 적정한 값을 찾아가는지 테스트함 # Linear model hypothesis = X * W # cost/loss function cost = tf.reduce_mean(tf.square(hypothesis - Y)) # Minimize: Gradient Descent Magic optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1) train = optimizer.minimize(cost) # Launch the graph in a session. sess = tf.Session() # Initializes global variables in the graph. sess.run(tf.global_variables_initializer()) for step in range(100): print(step, sess.run(W)) sess.run(train) ''' 0 5.0 1 1.26667 2 1.01778 3 1.00119 4 1.00008 ... 96 1.0 97 1.0 98 1.0 99 1.0 '''



[ Optimizer 적용 과 수작업(미분계산) 수치 비교]


 import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'


# Lab 3 Minimizing Cost

# This is optional

import tensorflow as tf

tf.set_random_seed(777)  # for reproducibility


# tf Graph Input

X = [1, 2, 3]

Y = [1, 2, 3]


# Set wrong model weights

W = tf.Variable(5.)


# Linear model

hypothesis = X * W


# Manual gradient

gradient = tf.reduce_mean((W * X - Y) * X) * 2


# cost/loss function

cost = tf.reduce_mean(tf.square(hypothesis - Y))


# Minimize: Gradient Descent Magic

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)

train = optimizer.minimize(cost)


# Get gradients

gvs = optimizer.compute_gradients(cost, [W])

# Optional: modify gradient if necessary

# gvs = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gvs]

==> gvc 수치를 필요에 따라서 변형적용이 가능함


# Apply gradients

apply_gradients = optimizer.apply_gradients(gvs)


# Launch the graph in a session.

sess = tf.Session()

# Initializes global variables in the graph.

sess.run(tf.global_variables_initializer())


for step in range(100):

    print(step, sess.run([gradient, W, gvs]))

    sess.run(apply_gradients)

    # Same as sess.run(train)



'''

# Apply gradients

0 [37.333332, 5.0, [(37.333336, 5.0)]]

1 [33.848888, 4.6266665, [(33.848888, 4.6266665)]]

2 [30.689657, 4.2881775, [(30.689657, 4.2881775)]]

3 [27.825287, 3.9812808, [(27.825287, 3.9812808)]]

4 [25.228262, 3.703028, [(25.228264, 3.703028)]]

...

96 [0.0030694802, 1.0003289, [(0.0030694804, 1.0003289)]]

97 [0.0027837753, 1.0002983, [(0.0027837753, 1.0002983)]]

98 [0.0025234222, 1.0002704, [(0.0025234222, 1.0002704)]]

99 [0.0022875469, 1.0002451, [(0.0022875469, 1.0002451)]]

'''

[ 참고자료 ]

https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/ 

http://agiantmind.tistory.com/176 

https://www.tensorflow.org/install/

https://github.com/hunkim/deeplearningzerotoall

http://www.derivative-calculator.net/

http://terms.naver.com/entry.nhn?docId=3350391&cid=58247&categoryId=58247    ==> 미분계산/공식

http://matplotlib.org/users/installing.html   ==>matplotlib 설치



 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid


인공지능 구현에 대한 글입니다.

글의 순서는 아래와 같습니다.


================================================

1. Tensorflow  Linear regression 소스코드 설명

2. placeholders 적용

  ==> data x,y를 미리 주지않고, 빈공간으로 그래프를 구성하고, 나중에 실행단계에서 숫자를 입력하는 방식임

  ==> 모델을 만들어 놓고, 나중에 data를 넘겨줄수 있음. 

3. Next step

  ==> cost 최소화 알고리즘 상세분석

4. 참고자료

=================================================

[Tensorflow Linear regression 소스코드 설명 ]


1. 라이브러리 IMPORT import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Lab 2 Linear Regression import tensorflow as tf tf.set_random_seed(777) # for reproducibility

2. DATA 할당


# X and Y data x_train = [1, 2, 3] y_train = [1, 2, 3] # Try to find values for W and b to compute y_data = x_data * W + b # We know that W should be 1 and b should be 0 # But let TensorFlow figure it out


3. 변수선언
W = tf.Variable(tf.random_normal([1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias')

# Our hypothesis XW+b


4. 가설 : X에 값에 따라 선형으로 변화하는 Y값의 관계를 직선의 공식으로 표현하고, 이를 파이선 문법으로 작성함



hypothesis = x_train * W + b



5. COST 함수 : 가설값과 실제 Y값의 차이를 최소화 하는 W를 찾는 함수



# cost/loss function cost = tf.reduce_mean(tf.square(hypothesis - y_train))



6. Gradient Descent : W 값을 기울기(미분값)*알파 값만큼 이동시키면서, COST 최소값을 찾아가는 함수

# Minimize optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) train = optimizer.minimize(cost) # Launch the graph in a session.


7. SESSION 선언 : 텐서플로우 노드를 실행하기 위해서는 SESSION선언후 실행이 가능함

sess = tf.Session() # Initializes global variables in the graph.


8. 실행

sess.run(tf.global_variables_initializer())

- 변수를 실행하기 위해서는 글로벌 로 초기화를 해주어야 함. # Fit the line for step in range(2001): sess.run(train) ==> Train을 실행하면, 하위단의 cost , hypathsis , w ,b 등이 따라서 실행이 되는 구조임 if step % 20 == 0: print(step, sess.run(cost), sess.run(W), sess.run(b)) # Learns best fit W:[ 1.], b:[ 0.]


9. 실행결과

- STEP이 진행될수록 Cost값 ( 실제값과 가설값의 차이 ) 가 작아지는 방향으로 W 값과 , B 값을 을 찾아가고 있음을 알수있음

- 여기서는 w값이 1에 수렴하고 , b는 0에 수렴하는것으로 보여집니다.

- 즉

X 1,2,3 / Y 1,2,3 을 가장 잘 나타내는 식은

H(X)=1*X+0 임을 알수있습니다. 0를 지나는 기울기 1인이 직선이 DATA를 나타내는 최적의 선 임을 알수있음


''' 0 2.82329 [ 2.12867713] [-0.85235667] 20 0.190351 [ 1.53392804] [-1.05059612] 40 0.151357 [ 1.45725465] [-1.02391243] ... 1920 1.77484e-05 [ 1.00489295] [-0.01112291] 1940 1.61197e-05 [ 1.00466311] [-0.01060018] 1960 1.46397e-05 [ 1.004444] [-0.01010205] 1980 1.32962e-05 [ 1.00423515] [-0.00962736] 2000 1.20761e-05 [ 1.00403607] [-0.00917497]


'''



[ placeholders 적용 ]

import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Lab 2 Linear Regression import tensorflow as tf tf.set_random_seed(777) # for reproducibility # Try to find values for W and b to compute y_data = W * x_data + b # We know that W should be 1 and b should be 0 # But let's use TensorFlow to figure it out W = tf.Variable(tf.random_normal([1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias') # Now we can use X and Y in place of x_data and y_data # # placeholders for a tensor that will be always fed using feed_dict # See http://stackoverflow.com/questions/36693740/
X = tf.placeholder(tf.float32, shape=[None]) Y = tf.placeholder(tf.float32, shape=[None]) ==> data x,y를 미리 주지않고, 빈공간으로 그래프를 구성하고, 나중에 실행단계에서 숫자를 입력하는 방식임
# Our hypothesis XW+b hypothesis = X * W + b # cost/loss function cost = tf.reduce_mean(tf.square(hypothesis - Y)) # Minimize optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) train = optimizer.minimize(cost) # Launch the graph in a session. sess = tf.Session() # Initializes global variables in the graph. sess.run(tf.global_variables_initializer()) # Fit the line for step in range(2001): cost_val, W_val, b_val, _ = \ sess.run([cost, W, b, train], feed_dict={X: [1, 2, 3], Y: [1, 2, 3]})
==> cost , w, b 실행을 한번에 명령을 줄수있음
==> cost data x,y를 여기서 주어줌 if step % 20 == 0: print(step, cost_val, W_val, b_val) # Learns best fit W:[ 1.], b:[ 0] ''' ... 1980 1.32962e-05 [ 1.00423515] [-0.00962736] 2000 1.20761e-05 [ 1.00403607] [-0.00917497] ''' # Testing our model print(sess.run(hypothesis, feed_dict={X: [5]})) print(sess.run(hypothesis, feed_dict={X: [2.5]})) print(sess.run(hypothesis, feed_dict={X: [1.5, 3.5]})) ''' [ 5.0110054] [ 2.50091505] [ 1.49687922 3.50495124] ''' # Fit the line with new training data for step in range(2001): cost_val, W_val, b_val, _ = \ sess.run([cost, W, b, train], feed_dict={X: [1, 2, 3, 4, 5], Y: [2.1, 3.1, 4.1, 5.1, 6.1]})
==> shape를 none으로 했기때문에,data 갯수는 필요한 만큼 줄수있음 if step % 20 == 0: print(step, cost_val, W_val, b_val) # Testing our model print(sess.run(hypothesis, feed_dict={X: [5]})) print(sess.run(hypothesis, feed_dict={X: [2.5]})) print(sess.run(hypothesis, feed_dict={X: [1.5, 3.5]}))

==> 학습이 완료된 hypothis 함수에 X값을 주고, Y값을 예측하는 과정임
''' 1960 3.32396e-07 [ 1.00037301] [ 1.09865296] 1980 2.90429e-07 [ 1.00034881] [ 1.09874094] 2000 2.5373e-07 [ 1.00032604] [ 1.09882331] [ 6.10045338] [ 3.59963846] [ 2.59931231 4.59996414]
"""

[참고자료 ]


https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/ 

http://agiantmind.tistory.com/176 

https://www.tensorflow.org/install/

https://github.com/hunkim/deeplearningzerotoall

 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid


인공지능 구현에 대한 글입니다.

글의 순서는 아래와 같습니다.


================================================

1. 프로그램 설치하기

2. 강의 소스코드 저장위치

3. 예제코드 실행 ( hellow tensorflow ! )

4. Nextstep

  - 코딩 실습

5. 참고자료

=================================================

[프로그램 설치하기]


1. 참고자료 ==>설치매뉴얼  http://agiantmind.tistory.com/176   ==> window10 매뉴얼이지만, WIN7에 설치해도 잘 잘동함.

2. Anaconda  TensorFlow   /  PyCharm 설치

     (참조) https://www.tensorflow.org/install/

  (1). Anaconda 설치

         Anaconda Download    ==>  Python 3.6  64-bit를 설치 

  (2) TensorFlow 설치

     [1] 시작프로그램 -> Anaconda Prompt 실행 ==> 관리자권한으로 실행

     [2]TensorFlow를 위한 환경 생성 (Python 3.5 버전으로 설치)

          C:>conda create -n TensorFlow python=3.5

     [3]TensorFlow 활성화

          C:>activate TensorFlow

          (TensorFlow) C:>  ==> 프롬프트 변경됨

     [4]PIP를 통해 TensorFlow 설치

         . CPU only version : (TensorFlow) C:>pip install tensorflow

         . GPU version : (TensorFlow) C:>pip install tensorflow-gpu   ==> NVIDIA 그래픽 카드 이용실 설치/별도 추가 TOOL 설치/가입 필요함

   (3)PyCharm 설치 및 환경 구성

      [1] PyCharm 다운/설치 (Community 버전 다운)

           PyCharm Download 

      [2] Create New Project 눌러 새로운 프로젝트 생성

      [3] 프로젝트 저장 위치 선택 후 Interpreter 항목에서 TensorFlow 설치된 환경의 Python 선택 필요

         interpreter 우측 톱니를 클릭하고 , ADD LOCAL 를 클릭해서 아래 화일을 선택함

          c:\users\dhp\anaconda3\envs\Tensorflow\python.exe

      [4] Project에 New --> Python File ==>코딩시행 ( hellow tensorflow! 출력하는 코딩입니다 )

       import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
sess = tf.Session()
hello = tf.constant('Hello, TensorFlow')
print(sess.run(hello))
print(str(sess.run(hello), encoding='utf-8')) # unicode --> utf-8


[ 강좌의 강의코드 저장위치]

    https://github.com/hunkim/deeplearningzerotoall



[Nextstep]

  - 코딩실습


[참고자료]

https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/ 

http://agiantmind.tistory.com/176 

https://www.tensorflow.org/install/

https://github.com/hunkim/deeplearningzerotoall

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

확인

 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid


Webserver 를 Github에 구축코자 합니다(https://david20120720.github.io/)


Github는 개발자들이 협업, 자료공유,커뮤티케이션을 할수있는 플랫폼으로 많이 알려져 있습니다(https://github.com)

오늘은 많은 기능들중에서 ,github page기능에 대해 글을 쓰고자 합니다.

page 기능은 github에 웹서버를 구축하는 개념입니다.

개발자들간에 협업을 할때, 유용한 기능인것 같습니다(장점: 도메인, 호스팅 서비스 무료,+다양한 기능들)


글의 순서는 아래와 같습니다.


=======================================================

1. github.com 계정만들기 ==> 세부사항은 생략하겠습니다.사이트에 접속하셔서 계정만드시면 됩니다.

2. page(웹페이지)용 저장소 만들기

3. page 저장소에 웹프로그램(html, java script ,구글지도 api등) 저장하기

4. 인터넷에 공개하기

5. 웹에 나타난 전체모습

   https://david20120720.github.io/


=======================================================



[ page(웹페이지)용 저장소 만들기 ]


1. github  계정을 만들면, 아래 화면을 볼수있습니다. 

  메뉴중 repositorie 항목이, 저장소 입니다.  그림상으로 4개가 등록이 되어 있음을 알수있습니다.

2. 새로운 저장소를 만듦니다. 홈페이지 프로그램을 저장할 저장소 입니다. 아래 화면의 "New"를 클릭합니다.


3.새로운 저장소의 이름은 "david20120720.github.io " 입니다. 향후 이 저장소 이름이 웹의 주소가 됩니다.

  public 선택 하시고, initiallize this ~ readme.md "를 선택하고 , 최하단 create~ 를 클릭하면, 저장소가 생성이 됩니다.  



[ page 저장소에 웹프로그램(html, java script ,구글지도 api등) 저장하기 ]

1. 아래 저장소에 웹프로그램을 저장합니다.

2. 주의사항

  . 아래 화일중 readme.md 화일은 저장소 생성시 자동으로 만들어진 화일입니다. 화일 내용에 " # david20120720.github.io "라고 입력이 되어있는데 , 이 내용을 삭제를 하시기 바랍니다. 삭제를 않하면 웹주소창에 주소치고 들어가면 불필요한 내용이 들어가서, 혼동이 생길수 있습니다.

3. 웹프로그램 소스화일을 유첨합니다. 간단한 소개화일입니다.

www git.zip


 

[인터넷에 공개하기]

 - Setting 메뉴선택

 - 하단의 github pages에서  source =>mater branch 선택후 save 한다





[웹에 나타난 전체모습]

1. 주소창에 " 개인아이디.github.io"로 들어가면 됩니다.

 - 메인창(index)

 

메뉴_나의 소개

 - 구글 진도 api를 넣어, 지도를 표현해 봤습니다.



메뉴_관심 분야




메뉴_최근 동향







 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid



K FRAM 박람회 (귀농,귀촌박람회)참관기


K FRAM 박람회 (귀농,귀촌박람회)참관기 입니다.

글의 순서는 아래와 같습니다.

-------------------------------------------

1.수경재배

2. 빗물이용 텃밭

3. 온실

4. 농업용 기계

  . 드론

5. 주택 

6. 귀농 컨설팅

-------------------------------------------


[수경재배]


구조

- 각층별 하단에 물이 흐르고 있음

  . 각 하단의 물에는 식물에 생장에 도움이 되는 약물이 포함되어 있음.

  . 최하단의 물통이 비치되어 있으며, 물은 지속적으로 순환함

- 각층별 상단에 LED 기 비추고 있음

  . LED는 식물의 합성을 최대화 할수있는 파장을 내고 있으며, 단위 LED 당 빛의 양이 많을수록 좋음(광의 양)

  . 참고로 청색,적색의 혼합광이 광합성에 도움이 됨

  . 광양을 최대화한 LED를 제작하는 업체가 본 박람회에 참여함.

- "묘종 셀"

  . 묘종이 담긴 그릇 : 씨앗과 스폰지(뿌리내릴수 있도록)등으로 구성되어 있음, 씨앗을 포함할수도 있고, 씨앗만 별도로 준비를 해도 무방함.

활용

- 인테리어 장식

  . 벽걸이 , 스탠드, 인테리어 디자이인등의 적용으로 집안의 인테리어가 가능함

  . 꽃을 좋아하시는 분들은 꽃을 심어서 인테리어 효과를 좀더 얻을수 있음

- 채소등 작물 재배

  . 상추등 채소를 심어서 식탁에 올리수도 있음.

- 교육

  . 자녀들에게 식물에 대한 교육도 가능하고, 물통의 물에 물고기를 넣어 키우면서, 물고기의 배설물이 식물에 영양분을 공급하는등의 생태계 교육이 가능함.

- 공기청정효과

  . 공기청정에 도움이 되는 식물재배

형태

  . 벽걸이형

    - 벽에 걸수있는 형태

  . 스탠드형

    - 집안에 스탠드형으로 세워놓는 형태임. 여러층으로 여러단으로 구성해서 식물을 제배할수 있음


 벽걸이형 

  


스탠드형[일반]                                                             인테리어 요소(집모양)을 추가한 형태임

     


[ LED]

  


[빗물활용 텃밭]


구조

- 빗물을 통과할 홀을 만들고, 홀을 통해 물통에 물을 채움

- 물통위에 식물을 심음(흙 이용)


활용

- 아스팔트 , 베란다, 보도블럭등 흙이 없는곳에 텃밭을 만들수 있음.

   


[온실]


구조

- 알루미늄 프레임

- 아크릴, pc등으로 단열벽 시공

- 프레임과 단열벽의 밀폐작업(고무)

활용

- 4계절 재배.

 


[농업용 기계 _ 드론 ]

구조

- 드론 + 약통 + 살수장치 + 배터리

- GPS 안테나

활용

- 방재작업.

    



[주택]


구조

- 이동식으로 구성됨

- 가격대는 평형에 따라서 1,500만원~ 5,000만원수준으로 파악됨

 


[귀농컨설팅]

 -지역(지방)에서 귀농을 하고자 하는 분들을 위해 컨설팅 서비스 함.