'K-MOOC/빅데이터와 머신러닝 소프트웨어'에 해당되는 글 8건

머신러닝 딥러닝을 GPU 를 이용하여 효율적으로 이용하기 위하여 분산하여 사용하는 것을 말한다 

 

이렇게 하면 좀더 분산하여 프로그램을 사용할 수 있기 때문에 효율성을 높일 수 있다 

 

블로그 이미지

Or71nH

,

떙큐 

이미지 분석 트레이닝 마스킹에 대하여 설명햇다 

 

'K-MOOC > 빅데이터와 머신러닝 소프트웨어' 카테고리의 다른 글

8주차 분산 머신러닝 딥러닝  (0) 2020.04.27
6주차 텐서플로우  (0) 2020.04.11
5주차 머신러닝 시스템 개요  (0) 2020.04.02
4주차 스트림 처리  (0) 2020.04.01
3주차 배치 분석  (0) 2020.03.24
블로그 이미지

Or71nH

,

 

 

  1. 그래프 안에서 데이터를 나타내는 것은 Tensor이고 그리고 그래프에서 수행하면서 상태를 보존하면서 가지고 있는 것을 나타내는 것이 변수 Variable에 해당합니다.
  2. 마지막으로 계산을 나타내는 것이 Operation입니다. Operation은 추상적인 계산을 나타내는 인터페이스이고, 실제로 해당하는 Operation을 구체적으로 구현한 것을 Kernel이라고 부릅니다.
  3. Kernel은 특정 디바이스 타입에서 수행될 수 있는 구체적인 구현체라고 보시면 되겠습니다.

 

### 모델 정의

Define a graph : h = ReLU(Wx + b)

import tensorflow as tf

b = tf.get_variable('bias', tf.zeros((100,)))
W = tf.get_variable('weights', tf.random_uniform((784, 100), -1, 1))

x = tf.placeholder(tf.float32, (None, 784))

h = tf.nn.relu(tf.matmul(x, W) + b)

코드는 적엇는데 아직 구동방법을 모름

 

### 구동 심볼릭 모드

import tensorflow as tf
import numpy as np

b = tf.get_variable('bias', tf.zeros((100,)))
W = tf.get_variable('weights', tf.random_uniform((784, 100), -1, 1))

x = tf.placeholder(tf.float32, (None, 784))

h = tf.nn.relu(tf.matmul(x, W) + b)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(h, {x: np.random.random(64, 784)})

@@ Linear Regression

import tensorflow as tf
import utils
DATA_FILE = "data/system_cpuutil_applatency.txt"

# Step 1:readin data from the .txt file
# data is a numpy array of shape(100000, 2 ) , each eow is a datapoint
data, n_samples = utils.read_system

# Step 2: create placeholders for X (CPU util) and Y (app latency)
X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y')

# Step 3: create weight and bias, initialized to 0
w = tf.get_variable('weights',initializer=tf.constant(0.0))
b = tf.get_variable('bias',initializer=tf.constant(0.0))

# Step 4: construct model to predict Y (app latency from CPU util)
Y_predicted = w * X + b

# Step 5: use the square error as the loss function
loss = tf.square(Y - Y_predicted, name='loss')

# Step 6: using gradient descent with learning rate of 0.001 to minimize loss
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)

## 수행하는곳
with tf.Session() as sess:
	# Step 7 : initialize the necessary variables, in this case, w and b 
    sess.run(tf.global_variables_initializer()
    
    # Step 8 : train the model
    for i in range(100): #run 100 epochs
    	for x, y in data:
        	# Session runs train_op to minimize loss 
            sess.run(optimizer, feed_dict={X:x,Y:y})
            
    # Step 9 : output the values of w and b
    w_out, b_out = sess.run([w.b])

 

### 구동 이거 모드 eager mode

import tensorflow as tf
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()

x = [[3.]]
m = tf.matmul(x, x)
print(m)
# tf.Tensor([[9.]], -(1, 1), dtype=float32)

 

### 사이즈가 고정된경우 좀더 빨리 할 수 있다

dataset = tf.data.FixedLengthRecordDataset([file1, file2, file3, ...])

iterator = dataset.make_one_shot_iterator()
input, label = iterator.get_next()
...
for i in range(100):
	...
    try:
    	while True:
        	sess.run([optimizer])
    except tf.errors.OutOfRangeError:
    	pass
        
dataset = dataset.shuffle(1000)
dataset = dataset.repeat(100)
dataset = dataset.batch(128)


dataset = dataset.map(lambda x:tf.one_hot(x, 10))
블로그 이미지

Or71nH

,

그래프 데이타 

모든곳을 둘러본다음 더이상 갈 곳 이 없는 곳이 블럭이 되며 모든것이 끝낫을때 정지한다

 

 

###머신러닝 종류

@@@Classical 머신러닝

1. Regression : 어떤변수와 다른 변수의 관계 찾기

2. Classlflcation : 스팸인지 아닌지 찾는거

3. Clustering : 여러 데이터 포인트들이 있을 때 더 근접한 데이터들끼리 모아서 만듬

4. Tocpic modeling : document 들이 있을때 각각의 document 들이 어떤 topic에 해당하는지 찾아냄

5. Collaborative filltering :추천하는 시스템에 많이 사용한다

6. Frequent pattern mining : 자주 같이 발생하는 패턴들을 찾아서 보는 것

7. Ranking : 여러가지 답중 어떤 것이 더중요한지 순서를 정함

 

###딥러닝 종류

1. Image classification : 이미지 픽셀 데이터를 입력으로 해당하는 이미지가 어떤 분류에 속하는지 파악하는 것

2. Speech-to-text, text-to-speech : 텍스트와 스피치를 변환해줌

3. Video understanding : 비디어 데이터를 보고 해당하는 내용을 텍스트 형태로 요약

4. Image, video style transfer : 하나의 이미지 비디오 스타일에서 다른 스타일로 변형을 하는 것

5. Text uderstanding-dialog : 쳇봇 시트템을 이용한 대화

6. Machine translation : 언어 변역 시스템

7. Ranking ads, feeds, news : 렝킹을 만드는 것 이라고 생각하면된다

8. Robot control, game play (e.g., GO) : 게임을 딥러닝하여 플레이함

9. Self-driving car : 스스로 운전하는 시스템

 

 

블로그 이미지

Or71nH

,

### 스트림 딜레이

인터넷이 없는 구간 즉 버퍼가 생길때의 차이가

시간차가 나며 데이터의 이동이 멈춘 상태

 

@@@Stream data

스트림의 데이타는 즉 보낸 시간

 

@@@Real-time processing

받은 시간 ??? 받는 시간이 보넨시간과 같은가??

 

### 처리 방법

1. element 마다 변환 방법

 

2. Aggregation

  1)그룹바이로 만든다

  2)윈도윙 (windowing) 어떤 시간에 따른 구릅으로 만듬

    1] Fixed window

        타임으로 나눔

     2] Sliding window

        조금식 겹치게 나눔

     3] Sessions window

        로그인 해놓은거 시작 그리고 끝을 따로만들어 

        중간에 계속 할 수 있도록 만든거 순서처리방식이 아님

 

### watermark

딜레이로 모든 데이터가 다왓나 확인하는것

 

간단히 요즘 AI 마이크 챗봇 같은느낌 말하고 기다리면 그걸로 끝인지 인지하는 듯한 느낌

 

### Stream Query Execution model 

1.Continuous Query

   전에 온 데이터를 가지고 있음 그리고 다음 데이터도 계속 받으며 처리함

2.Micro-batch

   제귀식으로 전에 데이터를 처리완료하고 다음 데이터를 받아서 찾아감

 

 

###Spark Structured Steaming

데이터를 스텍처럼 쌓는다

그리고 하나씩 처리한다

즉 데이터를 버리지 않고 계속 쌓아서 처리한다

적립식임 ㅇㅇ

 

###WordCount Program

from pyspark.sql import SparkSession
from pyspark.sql.functions import explode
from pyspark.sql.functions import split

spark = SparkSession \
     .builder \
     .appName("WordCountWithKafka")\
     .getOrCreate()
# Create DataFrame representing the stream of input lines
# from connection to a kafka server
lines = spark \
    .readStream \
    .format("kafka")\
    .option("kafka.bootstrap.servers", ip_addr:port) \ 
    .option("subscribe", "wc") \
    .load()
## Word Count Program ##
#Split the lines into words
words = lines.select(
    explode(split(lines.value." ")).alias("word")
)
#Generate running word count
wordCounts = words.groupBy("word").count()
#Start running the query that prints the running counts
# to the console
query = wordCounts \
    .writeStream \
    .queryName("wordcount_kafka") \
    .outputMode("complete")\
    .format("memory")\
    .start()
query.awaitTermination()

## Widow Operation ## 
words = ...#streaming DataFrame of schema
        #{ts: Timestamp, word: String}
# Group the data by window and word and compute the count of each group
windowedCounts = words.groupBy(
    window(words.ts, "3 minutes","1 minute"),
    words.word
).count()

## Spark structured Streaming ##
words = ...#streaming DataFrame of schema
        #{ts: Timestamp, word: String}
#Add watermark
windowedCounts = words
    .withWatermark("ts", "5 minutes")
    .groupBy(window(word.ts,"3 minutes","1 minute"), words.word)
    .count()

## Stream-Static Join##
# a static DataFrame about device info
deviceInfoDF = spark.read, ...
# a stream DataFrame about device signal
deviceSignalStreamDF = spark.readStream, ...

#inner equijoin with a static DataFrame
deviceSignalStreamDF.join(deviceInfoDF, "deviceType")

## Stream-Stream Join ## 
from pyspark.sql.functions import expr
# Joining two streams of data from dfferent sorces: posts and likes.
posts = spark.readStream, ...
likes = spark.readStream, ...

# Apply watermarks on event-time columns
postsWithWatermark = posts.withWatermark("postTime", "2 hours")
likesWithWatermark = likes.withWatermark("likeTime", "3 hours")

# Join with event-time constraints
postsWithWatermark.join(
    likesWithWatermark, 
    expr("""likePostId = postId AND 
         likeTime >= postTime AND
         likeTime <= postTime + 1 hour
         """)
)

    

 

헥헥 실험해 보고 싶다 

블로그 이미지

Or71nH

,