2018년 10월 15일 월요일

numpy

import numpy as np

def python_basie():
    a = np.array([[1, 2, 3], [3, 4, 5]])
    print(a[1])

    a, b = 3, 5
    c = 3, 5 # packing

    print(a, b, c)

    d, e = c # unpacking
    print(d, e)

    def f(a, b, c):
        print(a, b, c)

    f(1,2, 3)        # positional
    f(a=3, b=2, c=1) # keyword


# [] : List  : 중간중간 쉼표가 있음.
# [] : numpy.ndarray : 중간중간 쉼표가 없음.
# slicing. List와 ndarray 둘다 동작
def slicing():
    a = range(10)
    print(a)

    a = list(a)
    print(a)

    print(a[0])
    print(a[0:3]) # range()와 동일
    print(a[-1])
    print(a[3:])

    print(a[0:int(len(a) / 2)])
    print(a[int(len(a) / 2):])

    print(a[0:5])
    print(a[5:])

    print(a[:5])
    print(a[5:])
    print(a[:])    # 전체

    print(a[::2])  # 짝수 번째
    print(a[1::2]) # 홀수 번째

    print(a[-1::-1])
    print(a[::-1])

def np_basic():
    a = np.arange(6)
    print(a)
    print(a.shape, a.dtype, a.size, a.ndim)

    b = np.reshape(a, [2,3])
    print(b)

    b = a.reshape([2,3]) # OK
    print(b)

    b = a.reshape((2,3)) # OK
    print(b)

    b = a.reshape(2,3) # OK  python에서 튜플의 ()의 괄호는 생략 가능
    print(b)

    # broadcast 연산
    print(a+1)
    print(a*2)
    print(a/2)
    print(a>2)
    print(a ** 2)
    print(a[a>2]) # a> 2 항목만 뽑아 줌
    print(np.sin(a)) # universal function

    print(b+1)
    print(b*2)
    print(b/2)
    print(b>2)
    print(b ** 2)
    print(b[b>2]) # a> 2 항목만 뽑아 줌
    print(np.sin(b)) # universal function

    print(a+a) # vector operation
    print(b+b)


    a1 = np.arange(3)
    a2 = np.arange(6)
    a3 = np.arange(3).reshape(1,3)
    a4 = np.arange(3).reshape(3,1)
    a5 = np.arange(6).reshape(2,3)

    print("-"*50)
    print("a2", a2)
    print("a3", a3)
    print("a4", a4)
    print("a5", a5)
    print("-"*50)

    # scaler + vector ok : broadcast
    # shape이 다른 vector끼리는 NG !
    # 같은 shape 끼리는 연산 가능 OK ! : vector op
    # 1개 짜리 vector는 scale로 간주함. : broadcast

    # a1+a2 # ng : shape이 다르면 error
    print(a1+a3) # ok  : vector op
    print(a1+a4) # ok  : broadcast + broadcast
    print(a1+a5) # ok  : broadcast + vector op

    #print(a2+a3)
    #print(a2+a4)
    #print(a2+a5)
    #
    print(a3+a4)
    # print(a3+a5)
    #
    #print(a4+a5)

    c = np.arange(12)

    #아래 3가지는 모두 동일
    print(c.reshape(3,4).shape)
    print(c.reshape(-1,4).shape)
    print(c.reshape(3,-1).shape)

    d = c.reshape(3,4)

    # 아래 2가지는 모두 동일
    print(d.reshape(12))
    print(d.reshape(-1))

    np.random.seed(1)
    e = np.random.randint(100, size=12).reshape(3,4)
    print(e)

    print(np.max(e))
    print("axis=0", np.max(e, axis=0)) # 수직
    print("axis=1", np.max(e, axis=1)) # 수평

    print(np.argmax(e))
    print("axis=0", np.argmax(e, axis=0)) # 수직에서 가장 큰 위치 알려 줌
    print("axis=1", np.argmax(e, axis=1)) # 수평에서 가장 큰 위치 알려 줌
 
 
import numpy as np

import tensorflow as tf



a = np.arange(10)

print(a)



# 여러 항목을 한번에 꺼내는 방법

print(a[3], a[9])

# 는 아래와 동일하다. numpy는 "Index 배열" 지원 함.

print(a[[3, 9]]) # []를 하나더 해줘야 한다. 배열 행/열 index와 충돌 피하기 위해.



print("-"*50)



b = np.arange(12).reshape(3,4)

print(b)



print(b[0])

print(b[[0, -1]]) # 2개의 행데이터를 뽑아서 결합하는 방법. Index 배열 사용



print(b[::-1]) # 행 순서 뒤집기

print(b[-1, -1]) # 마지막 데이터.

# "Fancy index"이라 부름. 대괄호 안에 ,를 사용하는 문법. 차원마다 ,가 늘어남.

# 정수, slicing,

print(b[::-1, ::-1]) # 행과 열을 모두 뒤집기.



print(b.T) # transpose



# 문제 : 2차원 배열을 전치 형태로 출력하세요 (반복문, fancy index 사용)

for i in range(b.shape[-1]):

  print(b[:, i])



# 행을 가져오는 것도 사실은 열 인덱싱을 생략한 것.

for i in range(b.shape[0]):

  print(b[i, :])





def show_matmul(s1, s2):

    a = tf.constant(s1, shape=s1)

    b = tf.constant(s2, shape=s2)



    result = tf.matmul(a, b).shape

    print(" {} @ {} = {} ".format(s1, s2, result))



show_matmul([2,3], [3,2]) # 데이터가 아니라 shape을 넘긴 것임.

show_matmul([3,4], [4,2])





show_matmul([7, 2, 3], [7, 3, 2]) # tensorflow의 행렬 2차원까지밖에 없음. 
# 앞의 7은 7번 2차원행렬 연산을 할거란 의미. 2, 3과 3, 2는 매칭되어야 함.


show_matmul([2, 7, 3], [2, 3, 2])



# np squeeze : 의미 없는 차원을 없애 줌. 1차원만 없앨 수 있음. 2차원은 못 없앰.

x = np.array([[[[[0], [1], [2]], [[3], [4], [5]]]]])

print(x)

print(x.shape)



print(x.squeeze(axis=0).shape)

print(x.squeeze(axis=1).shape)

print(x.squeeze(axis=4).shape)

print(x.squeeze().shape) # 모두 한꺼번에 제거



np.random.seed(123)

t = np.random.random_integers(0, 100, 24).reshape(2, 3, 4) # 0~100에서 24개 생성

print("\n")

print(t)

print("\n")

print(np.argmax(t, axis=0), end='\n\n') # 0차원 2개 끼리 비교

print(np.argmax(t, axis=1), end='\n\n') # 1차원 3개 끼리 비교

print(np.argmax(t, axis=2), end='\n\n') # 2차원 4개 끼리 비교 

gradient descent

Single Variable
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [1, 2, 3]

# y = x  : True function# h(x) = wx : Hyperthesisdef cost(x, y, w):
   sum = 0   for a, b in zip(x, y):
       sum += (w*a - b)**2   return sum/len(x)

def show_cost():
    print(cost(x, y, 0))
    print(cost(x, y, 1))
    print(cost(x, y, 2))

    c = []
    for w in range(-10, 11):
      c.append(cost(x, y, w))

    print(c)
    plt.plot(range(-10, 11), c)
    plt.show()

    # 미분 : 기울기. 순간 변화량    #        x축으로 1만큼 움직일 때, y축으로 움직인 거리    #  y = x  1 = 1, 2 = 2, 3 = 3    #  y = 2x 2 = 1, 4 = 2, 6 = 3

def gradient_descent(x, y, w):
   gd = 0   for a, b in zip(x, y):
       gd += (w*a - b)*a # MSE cost w에 대해 미분시 x, 여기서는 a를 한번 더 곱해 주는 식이 된다.   return gd/len(x)

def update_gradient_descent(init=3, learning_rate=0.2, epoch=20):
   x = [1, 2, 3]
   y = [1, 2, 3]

   w = init
   for i in range(epoch):
       c = cost(x, y, w)
       g = gradient_descent(x, y, w)
       w -= learning_rate * g
       print(i, c)
   return w

w = update_gradient_descent()
print (5*w)
print (7*w)

# 문제 w 1.0으로 만드는 방법. Hyper parameter# 1. step을 올린다.# 2. learning late# 3. 초기값
# x 5 6일 대의 결과를 예측


Multi Variables
x1, x2, x3는 각각 피처. w1, w2, w3는 각각의 비중.
y는 실측

def loss(x1, x2, x3, y, w1, w2, w3):
    c = 0    for x_1, x_2, x_3, y_1 in zip(x1, x2, x3, y):
        c += (x_1*w1 + x_2*w2 + x_3*w3 - y_1) ** 2    
    return c / len(y)

def update_gradient_decent_one(x, y, w):
    d = 0    for x_1, y_1 in zip(x, y):
        d += (x_1*w - y_1)*x_1
    return d

def update_gradient_decent(x1, x2, x3, y, w1, w2, w3):
    w1 = w1 - 0.2 * update_gradient_decent_one(x1, y, w1)
    w2 = w2 - 0.2 * update_gradient_decent_one(x2, y, w2)
    w3 = w2 - 0.2 * update_gradient_decent_one(x3, y, w3)
    return w1, w2, w3

x1 = [1, 4, 5, 8] # 공부 시간
x2 = [3, 4, 7, 9] # 출석 일 수
x3 = [4, 6, 1, 3] # 학습 열정
y = [3, 5, 4, 7] # 성적

w1 = 3
w2 = 4
w3 = 5

for i in range(50):
    w1, w2, w3 = update_gradient_decent(x1, x2, x3, y, w1, w2, w3)
    print(loss(x1, x2, x3, y, w1, w2, w3))

2018년 9월 13일 목요일

TLS1.2 tests

up.mykings.pw:8888/update.txt

www.yahoo.co.jr
[기대] 메인 화면에 주황색 경고 메시지 없어야 함.

https://www.ssllabs.com/ssltest/viewMyClient.html#1532670339319&frame_loaded
[기대]
Your user agent has good protocol support.
Your user agent supports TLS 1.2, which is recommended protocol version at the moment.




2018년 8월 24일 금요일

bayes

Yi.t
t에 하나라도 생산되면 1
아니면 0

제약 조건 추가
Pi.t <= M(큰수) * yi.t


https://stats.stackexchange.com/questions/188319/bayes-theorem-with-multiple-conditions



https://www.analyticsvidhya.com/blog/2016/06/bayesian-statistics-beginners-simple-english/

2018년 7월 1일 일요일

Python matplot

import matplotlib.pyplot as plt

a = 3b = 2c = 1
year = [x for x in range(-100, 100)]
pop  = [x*(a)+b for x in range(-100, 100)]
#pop  = [x*x*x*x*(a)+x*x*b+x*c + d for x in range(-100, 100)]
plt.plot(year,pop)
plt.show()