반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

테슬라 주식이 최근 한참 빠졌다.

 

작년까지만 해도 생산이 제대로 안 된다는게 계속 발목을 잡았는데 올해 들어와서는 주문량 감소와 financial 이슈가 폭락을 이끌고 있다.

 

주문량 감소는 2018년 4/4분기와 비교했을 때 2019년 1/4분기 주문량이 줄었다는 건데....

글쎄 내 생각엔 전기차에 대한 수요 욕구는 점점 더 증가할 것이라고 판단하고 있다. 그래서 이게 그렇게 주가 폭락의 근본 원인이 될 수 있나? 하는 의문이 든다.

오히려 주문은 느는데 테슬라가 밧데리 물량이 확보 안된다든지 해서 미처 생산을 제대로 못하고 있어서 주가에 악영향을 주고 있는 상황이 오면 더 이해할 수 있겠다.

 

그리고 financial 이슈는 자금 부족 문제는 있을 수 있지만 그렇다고 테슬라가 망하거나 하는 상황은 가지 않을 것이라고 생각한다.

 

그래서 이 악재도 이렇게 까지 주가가 폭락 할 충분한 이유는 아니라고 본다.

 

내가 생각하는 테슬라 혹은 전기차 시장의 악재는 미국의 세일가스 라고 본다.

 

미국이 사우디를 제치고 석유 생산 세계 1위를 하도록 만든게 세일가스이다.

미국은 앞으로 이 세일가스를 계속 팔아야 된다.

그러면 앞으로 상당기간 내연 기관 차량이 이를 소비하는 한 구성 요소로 존재하는게 더 좋다.

 

이 이유가 미국 정부가 전기차의 부흥을 도와주는 정책을 세우지 않도록 만들고 있다고 본다.

 

하지만 그렇더라도 전기차의 수요는 점차 늘어날 것이고 메이저 기업들의 전기차 생산 설비 확산은 점점 더 광범위하게 일어날 것이라고 본다.

 

메이저 차량 회사들이 기존 내연기관 관련 인력을 감축하고 있는 것도 그러한 이유에서 일 것이다.

 

하여간 길게 글을 쓸 필요는 없을 것 같고 내 생각에 지금 테슬라 주가의 폭락은 과하다고 본다.

악재라고 얘기하는 것들은 일시적인 사안들이라고 본다.

더군다나 그 악재로 이렇게까지 폭락할 정도도 아니고....

 

2분기 실적 발표를 기점으로 크고 긴 상승 국면으로 전환하지 않을까 예측해 본다. (솔직히 그렇게 기대해 본다)

 

이런 나의 기대에 조금 더 힘을 보태주는 기사가 있어서 번역해 봤다.

 

 

 

Tesla Stock in 2019 Looks a Lot Like Netflix Stock in 2011

By Eddie YoonJune 4, 2019 5:30 a.m. ET

 

 

Tesla stock continues to drop, and has now fallen to roughly half its peak of $385. This is bad, but it is nowhere as bad as Netflix ’s 80% stock decline in 2011. Netflix’s decline was followed by an eight-year stretch of growth. Will Tesla shareholders be similarly rewarded? The question is whether Netflix’s 2011 is a comparable proxy for Tesla’s 2019.

 

테슬라 주가는 계속 하락세를 보이고 있으며, 지금은 이전 최고치 인 $ 385의 절반 정도로 하락했다. 안 좋은 주가이다, 하지만 2011 년 Netflix의 주가가 80 % 폭락한 정도는 아니다. 이 Netflix의 폭락 이후 넷플릭스는 8년간의 지속적인 성장을 보인다. 테슬라 주주들도 마찬가지로 보상받을 것인가? 문제는 Netflix의 2011 년이 테슬라의 2019 년과 비슷한 상황인지 아닌지다.

 

 

Back in 2011, Netflix had announced a jarring price increase, and CEO Reed Hastings announced it was separating its streaming business from its DVD by mail business. In a single quarter, Netflix lost 800,000 subscribers—just over 3% of its subscribers, then sitting at 24 million.

 

2011 년으로 돌아가서, 당시 Netflix는 (약간 분위기에 안 맞게) 가격 인상을 발표했으며, CEO인 Reed Hastings는 스트리밍 사업을 우편을 통해 DVD 를 배달하는 사업과 분리한다고 발펴했다. 당시 1 분기만에 넷플릭스는 총 가입자 수의 3 %를 상회하는 80 만 명의 가입자를 잃어 총회원수가 2400 만명이 되었다.

 

 

At the core of those costly decisions was the company’s belief in their category. They believed that streaming was the future and had a significant upside. And Netflix was 100% right. Now they have 60 million households in the U.S. and 150 million worldwide. The stock price is 39 times higher than its low point in 2011.

 

당시 리스크가 많은 이 결정의 핵심은 회사의 카테고리에 대한 믿음이었습니다. 그들은 스트리밍이 미래라고 믿었고 실제로 그 결정이 상승의 기폭제가 되었다. Netflix의 예상과 결정이 100 % 들어 맞은 것이다. 넷플릭스는 현재 미국에 6000 만 가구, 전 세계에 1 억 5000 만 가구를 회원으로 두고 있다. 주가는 2011 년 저점보다 39 배 상승했다.

 

 

Similarly, Tesla is spot on in their belief that demand for electric vehicles will grow exponentially. In 2018, electric vehicles were 2% of total new cars sold in the U.S. but 20% of Americans want an electric vehicle (per a study by AAA). Electric vehicles already have roughly a 10% market share in California. Tesla accounts for more than 60% of the share of growth of electric cars. The idea that Tesla’s 30,000 dip in deliveries in Q1 2019 versus Q4 of 2018 highlights a fundamental demand problem with either electric vehicles (which could easily number in the millions in the near future) or Tesla itself (since their products are beloved by consumers) seems like a stretch.

 

이와 비슷하게, 테슬라는 전기 자동차에 대한 수요가 기하 급수적으로 늘어날 것이라는 믿음을 가지고 있다. 2018 년 전기 자동차는 미국에서 판매 된 총 신차의 2 %를 기록하고 있지만 미국인의 20 %는 전기 자동차를 원하는 것으로 알려져 있다. (AAA에 의한 연구 당). 전기 자동차는 이미 캘리포니아에서 약 10 %의 시장 점유율을 가지고 있습니다. 테슬라는 전기 자동차의 성장 점유율의 60 % 이상을 차지합니다. 2018년 4사분기와 비교했을 때 2019년 1사분기의 차량 판매량이 3만대 줄어든 것은 근본적인 수요 이슈를 부각 시켰습니다. 즉 가까운 미래에 수백만에 다다를 것으로 생각되는 전기차 사업 혹은 테슬라 그 자체이든 시장은 확대 될 것이라는 것입니다. (테슬라의 제품은 고객들로 부터 사랑을 받고 있습니다.)

 

 

 

Netflix also believed in their pricing power, especially if they continued to improve their product (e.g., better recommendations and more content, including original, award-winning content). Netflix was also correct about this, and has continued to raise prices successfully. Even though Netflix has surely lost some subscribers as they’ve raised prices, total revenue and profits have grown enough to offset those losses.

 

Netflix는 또한 pricing power를 믿었습니다. 특히 제품 개선을 지속하는 경우 (예 : 더 나은 추천 기능이나 좀 더 많은 - 오리지널 이거나 수상경력이 있는 - 콘텐츠 등) pricing power는 더욱 증가할 것이라고 믿었습니다. Netflix의 이 예측도 들어 맞았습니다. 그 결과 그들은 지속적으로 가격을 올리는데 성공했습니다. 가격 인상으로 일부 고객을 잃은 것은 사실이지만 그들은 가격을 인상함으로서 총 매출과 수익은 그 손실을 상쇄하기에 충분했습니다. 

 

 

Tesla hasn’t increased its prices, but did see the $7,500 federal rebate for electric vehicles halved at the end of 2018—just at the same time their delivery volume dropped. Some analysts connected these two dots and see weakness in demand for Teslas. The more likely scenario is that this temporary price shock impacted quarterly sales by pulling some Q1 2019 sales earlier into Q4 2018 since the federal tax rebate phase-out was known for some time.

 

테슬라는 가격을 인상하지 않았지만 2018 년 말에 전기 자동차에 대한 7,500 달러의 연방 환급액이 절반으로 줄었습니다. 같은 기간 테슬라의 delivery 볼륨도 줄었습니다. 일부 분석가들은 이 둘을 근거로 Teslas에 대한 수요 약세로 보았습니다. 하지만 가장 그럴듯한 시나리오는 이러한 연방 세금 환급이 사라질 것이라고 알려져 그 이전인 2018년 1사분기의 수요를 증가시켰고 이는 2019년 1사분기 수요를 미리 끌어 당겼기 때문에 위와 같은 결과 - 2019년 1/4분기 매출이 3만대 감소- 가 나왔다는 겁니다.

 

 

The reality is that Tesla’s pricing power is strong. The best evidence of Tesla’s pricing power is that Tesla is attracting mainstream car owners as well as other luxury brand owners. Per CEO Elon Musk, the five most commonly traded in cars for a Tesla are Honda Accord, Honda Civic, Toyota Prius, Nissan Leaf, and BMW 3 series. It is no coincidence that from 2016 to 2018 Toyota Prius, Toyota Camry, Honda Accord, and Honda Civic all decreased a collective 15% in the US. This decline of nearly 190,000 cars is comparable to the over 180,000 Teslas sold in the US in 2018.

 

현실은 테슬라의 가격 결정권이 강하다는 것이다. 테슬라의 가격 결정력에 대한 가장 좋은 증거는 테슬라가 다른 럭셔리 브랜드 뿐만 아니라 주류 자동차 소비자를 끌어 들이고 있다는 것입니다. CEO 인 엘론 머스크 (Elon Musk)에 따르면 테슬라가 일반적으로 대체하는 5개의 차량은 혼다 어코드, 혼다 시빅, 토요타 프리우스, 닛산 리프, BMW 3 시리즈 등 입니다. 2016 년부터 2018 년까지 Toyota Prius, Toyota Camry, Honda Accord 및 Honda Civic의 판매량이 미국에서 15 % 감소했습니다. 차량 대수로는 약 19 만대의 감소한 것입니다. 이것은 2018 년에 미국에서 판매 된 180,000 대가 넘는 테슬라의 판매 대수와 비슷합니다.

 

 

Netflix and Tesla have also both struggled in some of the same ways, namely communication and execution.

 

Netflix와 Tesla는 communication and execution이라는 측면에서 비슷한 방식으로 어려움을 겪었습니다. 

 

 

Even though Netflix was ultimately right to increase prices and focus on streaming, it was clumsy in how it communicated these changes to customers. The timing of some of these moves was also off: it could have allowed DVD by mail to slowly fade, and introduced its price hike when it launched House of Cards, its first major success in original content. These were unforced errors. Similarly, Tesla has had similar, self-inflicted struggles on communication and execution.

 

넷플 릭스가 궁극적으로 가격을 올리고 스트리밍에 집중하는 것이 옳았지 만 이러한 변화를 고객에게 어떻게 전달했는지는 서툴 렀다. 이러한 움직임의시기는 또한 벗어났습니다. 우편으로 DVD를 배달하는 서비스를 좀 더 천천히 사라지도록 할 수 있었고 원본 콘텐츠로 첫번째 메이저급 성공을 거둔 House of Cards의 상영이 시작됐을 때 가격 상승을 발표할 수도 있었다. 즉 발표 타이밍에서 서툴렀다는 것이다. 이것은 자체적인 오류라고 할 수 있다. 비슷하게, 테슬라는 communication and execution 에 있어 자초한 어려움을 비슷하게 겪고 있다.

 

 

The difference between the two firms is that since those earlier stumbles, Netflix’s execution has gotten smoother and their communication more empathetic. Netflix has continued to raise prices, using a good/better/best pricing strategy to give customers a feeling of control. Netflix has also recognized that it’s costly to try and be great at everything; this is why they’ve migrated to Amazon Web Services, even though Amazon Prime Video is a direct competitor. They’ve managed to focus on improving and expanding their content and geographies.

 

두 회사의 차이점은 넷플 릭스의 사태가 더 일찍 일어 났으므로 넷플 릭스의 execution이 좀 더 원활해졌고 communication은 좀 더 공감을 얻었다는 겁니다. Netflix는 고객에게 고객 자신이 가격을 컨트롤 하고 있다는 느낌을 주기 위해 good/better/best라는 가격 정책을 사용하면서 가격을 인상했습니다. Netflix는 또한 모든 것에서 최고가 되려고 하는 것이 너무 많은 비용을 초래한 다는 것을 깨달았습니다. 그렇기 때문에 Amazon Prime Video가 직접적인 경쟁자 임에도 불구하고 Amazon Web Services로 마이그레이션 한 이유입니다. 그들은 콘텐츠를 개선하고 서비스 지역을 확장하는데 초점을 맞춰서 사업을 진행했습니다. 

 

 

Meanwhile, Tesla seems to be trying to do too many things at once, perhaps one reason they are struggling on deliveries. Musk continues to juggle roles across Tesla, Space X, and the Boring Company, and to occasionally issue SEC-incensing tweets.

 

그 사이에, Tesla는 한꺼번에 너무 많은 것을 시도하고있는 것처럼 보인다, 아마 납품에 어려움을 겪고 있는 것도 한 이유일 것이다. 머스크는 테슬라, 스페이스 X, the Boring Company에서 계속 자신의 역할을 수행하고 있다. 그리고 때때로 SEC를 건드리는 트윗도 하고 있다. 

 

 

While Tesla is right about consumer demand and their pricing power, they should also remember that a successful company takes more than that. Being right isn’t always enough.

 

테슬라의 소비자 수요와 가격 결정력에 대해서는 옳다고 생각하지만 성공적인 기업은 그 이상을 필요로한다는 것을 기억해야합니다. 옳다는 것이 항상 충분한 것은 아닙니다.

 

Eddie Yoon is the founder of EddieWouldGrow, a think tank and advisory firm on growth strategy, and the author of the book Superconsumers and a monthly newsletter. Find him on Twitter and Instagram @eddiewouldgrow.

반응형


반응형

AWS DeepRacer League

 

누구나 이용할 수있는 세계 최초의 자율주행 레이싱 리그에 오신 것을 환영합니다.

re:Invent 2019에서 AWS DeepRacer Cup에서 우승해 상금, 영예, AWS DeepRacer Championship Cup을 획득하세요. 매월 열리는 가상 Circuit 레이스에서 온라인으로 경쟁하거나 전 세계 Summit Circuit 경주 행사에서 직접 경쟁 할 수 있습니다.

 

Standings: Check out the live leaderboard and latest race results

view Leaderboards >>

 

AWS DeepRacer console을 통해 가상공간에서 레이스

현재 진행 중인 레이스 - Kumo Torakku

 

일본의 스즈카 트랙에서 영감을 얻은 Kumo Torakku 서킷 레이싱에서 우승해 re:Invent로 가는 경비 지원을 받으세요.  후지산을 보며 도쿄의 거리를 달려 승리하세요. 그리고 포인트와 상금을 획득하세요. 그리고 AWS re:Invent 2019에서 열리는 AWS DeepRacer Championship Cup 출전권도 받으세요.

 

AWS Free Tier를 사용하면 최대 10 시간동안 훈련을 무료로 진행할 수 있습니다. 그러니까 AWS DeepRacer League에 아무런 비용을 들이지 않고 참여해 보세요. 

 

Race Online       View Live Leaderboard  

 

 

AWS DEEPRACER TV

Take a step inside the AWS DeepRacer League. Episode 1 follows the competition to Amsterdam, featuring developers of all skill levels hoping to qualify for a chance to win the Championship Cup at AWS re:Invent 2019. Tune in now to learn more about their strategy and how you can build and tune a model for a chance to win!

 

AWS DeepRacer League를 향해 한걸음 내디뎌 보세요. 에피소드 1은 암스테르담에서의 경기가 나옵니다. AWS re:Invent 2019 에서 열리는 Championship Cup에서 우승하는 것을 목표로 하는 다양한 수준의 개발자들이 나옵니다. 그들의 전략에 대해 배워 보세요 그리고 여러분은 우승을 위해 어떻게 모델을 만들어 갈 것인지 생각해 보세요.

 

 

 

Pick a race

 

개발자는 매월 공개 될 유명한 raceways에서 영감을 얻은 가상 트랙을 통해 Virtual Circuit에서 경쟁함으로써 테스트에 자신의 기술을 적용 할 수 있습니다. re:Invent 2019에서 열리는 AWS DeepRacer Championship Cup에 대한 경비와 경품을 얻기 위해 경쟁 할 수 있습니다.

20 개의 AWS Summit 중 아무 Summit이나 선택해서 직접 참가하세요. (참여하고 싶으면 여러 Summit에 참여하실 수 있습니다.) 워크샵을 통해 re:MARS 및 re:Invent 2019에서 모델을 어떻게 만들고 트레이닝 시킬 지에 대해 도움을 드릴 겁니다. 여러분이 트레이닝 시킨 모델을 집으로 가져 가실 수도 있습니다. 그리고 그 모델을 테스트하고 엑스포에서 그것을 가지고 경쟁하실 수 있습니다.

 

See Full Schedule and Standings

 

Pick up some racing tips

 

기계 학습을 처음 사용 하던지 기존 스킬을 기반으로 준비하든, 우리는 당신이 경주 준비를하는 것을 도울 수 있습니다. e- 러닝 수업 인 AWS DeepRacer : 강화 학습 학습에 의해 시작할 수 있습니다. 약 90 분 후에 보강 학습 (자율 차량 교육에 이상적인 기계 학습의 한 분야)의 기본 사항과 AWS DeepRacer - 트랙을 누빌 준비가되었습니다!

 

Take the e-learning course

 

 

Race, win prizes, score points

 

Summit Circuit 레이스 또는 Virtual Circuit 레이스에서 경쟁하십시오. 경쟁하는 레이스 수에는 제한이 없습니다. Virtual Circuit 또는 Summit Circuit 레이스 중 하나만이라도 1등을 하면 라스베가스에서 열리는 AWS re:Invent에서 열리는 AWS DeepRacer final round에 참가하는 경비를 지원받으실 수 있습니다. 각 레이스의 10등까지는 AWS DeepRacer 자동차를 받으실 수 있습니다. 

각 레이스마다 참여하시면 포인트를 받게 됩니다. 2019년 말에 이 포인트들의 합계를 가지고 등수를 가립니다. 각 Circuit의 우승자에게는 re:Invent 2019의 AWS DeepRacer knockout(final) 라운드에 참가하는 경비를 지원 받으실 수 있습니다. 자세한 내용은 AWS DeepRacer 공식 규칙을 참조하십시오.


레이스에 참가하면 2019 AWS DeepRacer League Champion이 될 수 있습니다!

 

Learn more about points and prizes

 

 

 

2차 Virtual Race 오픈

 

Kumo Torakku Track

 

 

 

 

 

반응형


반응형

Stragit Track 에서 두번 훈련 시킨 모델을 Clone 해서 곡선이 있는 다른 트랙에서 훈련 시키기로 했다.

나머지 트랙 중 가장 간단한 트랙인 Oval Track에서 먼저 훈련을 시켰다.

 

 

reward_function을 약간 수정했는데....

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    reward=1e-3
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    steering = params['steering_angle']
    speed = params['speed']
    all_wheels_on_track = params['all_wheels_on_track']
    
    if distance_from_center >=0.0 and distance_from_center <= 0.03:
        reward = 1.0
    
    if not all_wheels_on_track:
        reward = -1
    else:
        reward = params['progress']
        
    # Steering penality threshold, change the number based on your action space setting
    ABS_STEERING_THRESHOLD = 45

    # Penalize reward if the car is steering too much
    if steering > ABS_STEERING_THRESHOLD:
        reward *= 0.8
        
    # add speed penalty
    if speed < 2.0:
        reward *=0.80
    
    return float(reward)

 

일단 여긴 곡선 구간이 있으니 핸들 꺾는 걸 조금 더 여유를 주어야 겠다고 생각했다.

이전 직선 트랙에서는 15도로 제한을 뒀는데 여기서는 45도 까지 여유를 주었다.

그 이상 핸들을 급하게 꺾으면 점수가 20% 깎이도록 했다.

 

그리고 곡선구간에서는 아무래도 속도를 줄여야 하니 제한을 2.0으로 고쳤다.

이전엔 2.5 였다.

 

이렇게 고치고 나서 100분 동안 훈련을 시켰다.

 

한 30분 쯤 지나면서 부터 높은 reward가 나오기 시작했다.

그리고 reward 저점도 그 이후부터는 1.50k를 넘었다.

 

그 이후부터는 reward의 고점이 대략 8.0k 내외이고 그런 고점이 나오는 빈도수도 크게 변화를 보이지는 않은 것 같다.

 

아마 위 reward_function으로 이 구간에서는 그렇게 크게 performance가 발전하기는 힘들 것 같다.

 

reward_function을 조금씩 고쳐가며 계속 훈련을 하고 싶지만.. 한번 그렇게 하는데 별도로 돈을 내야하기 때문에 맘 놓고 여러가지를 시도 하지 못하겠다.

 

일단 평가 결과는 아래와 같다.

 

3번 시도 중 한번만 성공했고 실패한 것도 트랙을 35%만 돌았다.

점수가 아주 저조하다.

 

성공했을 때의 기록은 23.797초 이다.

 

 

일단 이 트랙은 이 정도면 됐고 다음 연습 트랙은 어제 끝난 AWS Deepracer League - Viertual Circuit London Loop 에서 사용한 London Loop Track에서 훈련을 시키기로 결정 했다.

 

 

이 리그는 4/29 부터 5/31 까지 한달간 진행된 리그이다.

나는 늦게 시작해서 이 리그에는 참가를 못 했다.

6월부터 시작하는 Vertual league에 참가할 계획이다.

 

일단 London Loop Track에서 사용할 reward_function은 아래처럼 고쳤다.

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    reward=1e-3
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    steering = params['steering_angle']
    speed = params['speed']
    all_wheels_on_track = params['all_wheels_on_track']
    
    if distance_from_center >=0.0 and distance_from_center <= 0.03:
        reward = 1.0
    
    if not all_wheels_on_track:
        reward = -1
    else:
        reward = params['progress']
        
    # Steering penality threshold, change the number based on your action space setting
    ABS_STEERING_THRESHOLD = 30

    # Penalize reward if the car is steering too much
    if steering > ABS_STEERING_THRESHOLD:
        reward *= 0.8
        
    # add speed penalty
    if speed < 1.5:
        reward *=0.80
    
    return float(reward)

 

여기서도 핸들 각도와 스피드 제한 부분을 조금 수정했다.

 

일단 핸들 각도는 이전보다 좁은 30도를 줬다. 

이 트랙이 이전 트랙보다 조금 더 급한 커브가 있지만 속도를 더 낮추는 걸로 대비하기로 했다.

 

스피드는 이전에 2.0 의 제한을 두던것을 1.5로 낮췄다.

 

훈련시간은 큰 맘 먹고 300분으로 했다. 

그 결과는 아래와 같다.

 

 

여기도 보니까 30분 이후부터 조금씩 개선되는 것 같더니 1시간 이후부터 저점이 3.0K를 어느 정도 유지하는 싸이클을 보였다.

 

그 이후는 그게 개선되지는 않았지만 3시간 지나면서 최고점인 9.69K를 찍기 시작했다.

 

훈련 후 진행한 평가 결과는 아래와 같다.

 

 

3번 중 2번 완주 했고 기록은 24초 정도 이다.

실패한 1번도 트랙을 80% 진행했다.

Oval Track과 비교해서 아주 만족스런 결과이다.

 

좋다.

 

 

참고로   AWS Deepracer League - Viertual Circuit London Loop 수상자들의 기록은 다음과 같다.

 

 

9초,10초, 11초.... 24초인 내가 낄 자리는 없다.

쟤네들은 어떤 reward_function을 썼고 Hyperparameter configuration은 어떤 변동을 주었는지 그리고 어떤 훈련을 얼마나 시켰는지 궁금하다.

 

다음주 2차 Virtual League에서 사용하는 Track 이 발표되면 그 트랙에서 집중적으로 훈련을 시킬 계획이다.

반응형


반응형

오늘은 모델을 생성하고 Training 시키고 Evaluation까지 시키고 난 후 볼 수 있는 여러 정보들을 살펴 봤다.

 

우선 Reward Graph를 보면 Refresh 버튼 밑에 메뉴항목이 있다.

View in metrics와 View logs가 있는데..

 

일단 View in metrics로 가 보자.

 

그러면 Cloud Watch의 Total reward over time 페이지로 이동한다.

 

AWS Cloud Watch는 AWS 클라우드 서비스들에 대한 모니터링 정보를 제공하는 서비스이다.

 

Amazon CloudWatch is a monitoring service for AWS cloud resources and the applications you run on AWS. You can use Amazon CloudWatch to collect and track metrics, collect and monitor log files, set alarms, and automatically react to changes in your AWS resources.

 

이 Total Reward over time 페이지는 아래와 같다.

 

Reward Graph가 좀 더 자세하게 나오고 그 아래에는 뭔지 모를 4개의 탭이 있고 더 뭔지 모를 여러 정보들이 있다.

 

뭐 별로 눈길을 끄는게 없어서 다음으로 패스.

 

View logs를 클릭 해 봤다.

 

역시 AWS Cloudwatch 서비스 페이지로 넘어갔다.

 

 

 

 

여기에는 로그 정보들이 있다.

매일 코딩을 하다보면 어쩔 수 없이 뚫어져라 볼 수 밖에 없는 게 로그 정보들이라서 이건 좀 친숙하다.

 

 

우선 첫번째 링크는 Lamda로그인 것 같은데 여기엔 별 정보가 없었다.

 

두 번째 로그는 시뮬레이션 관련 로그인 것 같다.

이 정보들을 활용하는 법을 알면 유용한 정보일 수 있을 것 같다.

아직은 잘 몰라서 그냥 이런게 있다는 것만 알고 넘어간다.

 

마지막 세번째 링크가 Training 관련 로그이다.

 

여기엔 좀 뭔가 알아 먹을 것 같은 로그 정보들이 있다.

이건 직선 트랙에 디폴트 reward_function 을 사용한 트레이닝 로그인데 여기에 에피소드와 이터레이션 정보가 있다.

 

30분간 트레이닝을 시켰는데 마지막 에피소드는 372 이다.

아마 372번 훈련을 한 것이다.

 

1개의 iteration에는 20개의 에피소드가 있다. 

그래서 총 18개의 iteration이 있다.

 

각 에피소드 별로 Total Reward와 Steps 정보가 있다.

 

이 로그에는 대충 이런 정보들이 있다.

 

그 외에 이 로그 시작 부분에 각 종 환경 변수나 파라미터 정보들이 있다.

 

 

 

 

 

그 다음 Evaluation section에는 평가 결과 정보가 있다.

평가는 3번 하는 것 같다.

평가 작업은 계속 할 수 있는데 이 서비스는 별도의 요금을 내는 것 같아서 여러번 시도하지는 않았다.

 

그 다음 Training Configuration section에는 여러 config 정보를 볼 수 있다.

 

Reward function의 Show 버튼을 누르면 이 모델에서 사용한 Reward function을 볼 수 있다.

그리고 그 밑에 Action space 정보를 볼 수 있는 버튼이 있다.

 

Framewark 은 Tensorflow를 사용했고 Reinforcement learning algorithm은 PPO를 사용했다는 정보가 있다.

 

그리고 마지막은 Hyperparameter 정보들이 있다.

 

지금까지 직선 트랙에서 두 번 훈련 시켰다.

 

다음은 곡선이 들어간 트랙에서 훈련을 시켜보기로 했다.

 

 

 

 

 

 

반응형


반응형

본격적으로 AWS Deepracer를 시작했다.

첫번째 모델을 만들었다.

 

일단 트랙은 제일 간단한 것으로 선택 하고 Speed는 5로 선택.
직선도로니까 빠르게 달리게 만드는게 더 좋을 것 같아서.
나머지는 다 디폴트.


Reward_function도 그냥 디폴트 사용하고 시간은 30분
참고로 디폴트 함수는 아래와 같다.

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    
    # Calculate 3 markers that are at varying distances away from the center line
    marker_1 = 0.1 * track_width
    marker_2 = 0.25 * track_width
    marker_3 = 0.5 * track_width
    
    # Give higher reward if the car is closer to center line and vice versa
    if distance_from_center <= marker_1:
        reward = 1.0
    elif distance_from_center <= marker_2:
        reward = 0.5
    elif distance_from_center <= marker_3:
        reward = 0.1
    else:
        reward = 1e-3  # likely crashed/ close to off track
    
    return float(reward)

 

소스코드를 보니 트랙 중앙선 가까이 가면 점수(reward)를 더 많이 주는 간단한 로직이다.

30분 트레이닝 시키고 곧바로 Evaluate
결과는 조금 있다가…

 

 

 


이 첫번째 모델을 clone 해서 두번째 모델을 만들었다.
다 똑같고 reward function 함수만 내가 원하는 대로 조금 바꾸었다.

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    reward=1e-3
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    steering = params['steering_angle']
    speed = params['speed']
    all_wheels_on_track = params['all_wheels_on_track']
    
    if distance_from_center >=0.0 and distance_from_center <= 0.03:
        reward = 1.0
    
    if not all_wheels_on_track:
        reward = -1
    else:
        reward = params['progress']
        
    # Steering penality threshold, change the number based on your action space setting
    ABS_STEERING_THRESHOLD = 15

    # Penalize reward if the car is steering too much
    if steering > ABS_STEERING_THRESHOLD:
        reward *= 0.8
        
    # add speed penalty
    if speed < 2.5:
        reward *=0.80
    
    return float(reward)

 

이전에 썼던 디폴트 함수와는 다르게 몇가지 조건을 추가 했다.
일단 중앙선을 유지하면 좀 더 점수를 많이 주는 것은 좀 더 간단하게 만들었다.
이 부분은 이전에 훈련을 했으니까 이 정도로 해 주면 되지 않을까?
그리고 아무 바퀴라도 트랙 밖으로 나가면 -1을 하고 모두 트랙 안에 있으면 progress 만큼 reward를 주었다.
Progress는 percentage of track completed 이다.
직진해서 결승선에 더 가까이 갈 수록 점수를 더 많이 따도록 했다.
이건 차가 빠꾸하지 않고 곧장 결승점으로 직진 하도록 만들기 위해 넣었다.
그리고 갑자기 핸들을 과하게 돌리면 차가 구르거나 트랙에서 이탈할 확률이 높으니 핸들을 너무 과하게 돌리면 점수가 깎이도록 했다. (15도 이상 핸들을 꺾으면 점수가 깎인다.)
그리고 속도도 너무 천천히 가면 점수를 깎는다.

속도 세팅이 최대 5로 만들어서 그 절반인 2.5 이하고 속도를 줄이면 점수가 깎인다.


이렇게 조건들을 추가하고 Training 시작.
이건 좀 복잡하니 트레이닝 시간을 1시간 주었다.

이 두개의 모델에 대한 결과는…

 

딱 보니 첫번째 디폴트 함수를 사용했을 때는 시간이 갈수록 결과가 좋게 나왔다.
그런데 두번째는 시간이 갈수록 실력이 높아지지는 않는 것 같다.


너무 조건이 여러개 들어가서 그런가?

 

 


생각해 보니 조건을 많이 넣는다고 좋은 것은 아닌것 같다.
일반적으로 코딩을 하다 보면 예외 상황을 만들지 않게 하기 위해 조건들을 아주 많이 주는 경향이 있는데 이 인공지능 쪽은 꼭 조건을 많이 줄 필요는 없을 것 같다.


앞으로 인공지능 쪽을 하다보면 일반 코딩에서의 버릇 중에 고칠 것들이 많을 것 같다.
Evaluation 결과를 보면 두개의 차이가 별로 없다. 
두 모델 모두 3번중 2번 완주 했고 완주시간도 비슷한 것 같다.
조건을 쪼금 더 준 Model 2 가 좀 더 낫긴 하네. (0.2 ~0.3 초 더 빠르다.)
다음은 곡선이 있는 다른 트랙으로 훈련을 시킬 계획이다.


그런데 곡선이 있는 트랙에서는 스피드가 무조건 빠르다고 좋은 건 아닌 것 같다.
내가 스피드를 5로 주었는데 Clone을 만들어서 할 때는 이 스피드를 조절하지 못하는 것 같다.


곡선 구간에서는 reward_function을 어떻게 주어야 하지?

반응형


반응형

AWS DeepRacer 공부를 시작하고 나서 뜻밖의 요금이 징수되서 조금 놀랐다.

지난주 매일 1달러씩 부과 되던 NAT Gateways 서비스를 언제 세팅 했는지 몰랐었다.

여하튼 아마존 Support 서비스의 도움을 받아서 해당 서비스를 Delete 한 이후 요금은 더이상 부과 되지는 않았는데...

문제는 그걸 지우고 난 이후 Deepracer model을 생성하면 에러가 발생해서 일을 더이상 진행 할 수가 없었다.

 

도저히 안되서 새로운 account를 생성하고 Deepracer Model을 하나 생성했다.

 

그랬더니 모델과 더불어 NAT Gateways가 생성되더라.

이제 알았다. 처음 DeepRacer를 시작하기 위해 account resources를 생성할 때 이 NAT Gateway가 생성된다는 것을....

 

이 단계를 완료하면 NAT Gateways가 생성돼 매일 1달러씩 청구된다.

참고로 아래는 DeepRacer 모델을 하나 생성하면 청구되는 금액들이다.

 

 

* Data Transfer에서 $0.010 per GB - regional data transfer - in/out/between EC2 AZs or using elastic IPs or ELB 가 5기가가넘어서 5센트가 청구됐다. 

* 그 다음 EC2에서 NAT Gateway가 생성과 연계해서 2.10 달러가 청구 됐다.

* 여기서 NAT Gateway는 매일 1달러씩 청구되게 돼 있다.

* 그 다음은 시뮬레이터 서비스인 RoboMaker 서비스에 대해 1.52달러가 청구됐고 SageMaker는 30센트가 청구됐다.

 

다른 서비스들은 사용하면 사용한 시간만큼만 내는데 NAT Gateway는 24시간 계속 돌아가기 때문에 매일 1불씩 내야 한다.

사용하지 않을 때 Stop 할 수도 없는 것 같다.

 

하루에 1달러이면 아무것도 아니라고 생각할 수 있지만... 아무것도 하지 않는데도 청구가 되니 속이 쓰렸다.

 

그래서 AWS Support Case를 하나 더 Raise 했다.

 

오늘 아침에 했는데 퇴근 할 때 쯤 답변이 오더라구.

 

 

다음은 답변 내용...

 

Hey there! This is Merlyn, your AWS Billing & Accounts specialist. I hope you are having a wonderful day! I understand you have some concerns about the DeepRacer pricing and you bill. Worry not as I'm here to help.


DeepRacer의 가격 책정과 청구서와 관련 우려가 있다는 것에대해 이해합니다. 걱정마세요. 제가 도와드릴테니까요.

With AWS DeepRacer console services, there are no charges for driving the AWS DeepRacer car or upfront charges. You will only pay for the AWS services you use. You will be billed separately by each of the AWS services used to provide the AWS DeepRacer console services such as creating and training your models, storing your models and logs, and evaluating them, including racing them in the virtual simulator or deploying them to their AWS DeepRacer car. You will see the bill for each service on your monthly billing statement.

AWS DeepRacer console services는 AWS DeepRacer 차량을 driving 하는데에 대한 가격 책정이나 선불로 어떠한 돈을 낼 필요가 없습니다. 당신이 AWS services를 사용한 것에 대한 요금만 지불 하시면 됩니다. AWS DeepRacer console services를 통해 사용하시는 AWS services들에 대해 각각의 사용료가 따로 청구 될 것입니다. 예를 들어 당신의 모델들을 생성하고 훈련하는 것 그리고 그 모델들이나 로그들을 저장하는 것, 그 모델들을 평가하는 작업, 가상 시뮬레이터에서 모델의 레이싱을 하거나  AWS DeepRacer car에 배치하는 일들에 대해 따로 사용료가 부과 됩니다. 

Upon first use of AWS DeepRacer simulation in the AWS console, new customers will get 10 hours of Amazon SageMaker training, and 60 Simulation Unit (SU) hours for Amazon RoboMaker in the form of service credits; $6 for SageMaker, $24 for RoboMaker and $34 for NAT Gateway. The service credits are available for 30 days and applied at the end of the month. A typical AWS DeepRacer simulation uses up to six SUs per hour, thus you will be able to run a typical AWS DeepRacer simulation for up to 10 hours at no charge.


AWS console에서 AWS DeepRacer simulation을 처음 사용하는 새 고객에게는 10시간 동안 Amazon SageMaker training과 Amazon RoboMaker에 대해 60 Simulation Unit (SU) 시간에 대해 service credits이라는 형태로 무료 사용하실 수 있는 기회를 드립니다. SageMaker는 $6 , RoboMaker $24 그리고  NAT Gateway는 $34 입니다. 이 service credits은 30일간 사용 가능하고 그 달의 말에 적용됩니다. 일반적으로  AWS DeepRacer simulation 사용은 시간당 six SUs이므로 당신은 AWS DeepRacer simulation을 10시간 동안 무료로 사용하실 수 있습니다. 

Please visit the link below for more pricing information:

자세한 가격 정보는 아래 링크를 참조하세요.

https://aws.amazon.com/deepracer/pricing/ 

This inquiry is a bit out of our scope. Here in the Billing and Accounts department we don’t handle technical questions. Please note that AWS unbundles technical support in order to lower the prices of the services themselves instead of billing it to all customers disregarding if they’d like to use it or not. However, if technical support is required, I would like to tell you we offer several Premium Support plans starting at just $29 a month, which enables you to speak to an engineer by email, chat, or phone depending on what support plan you choose.


당신의 요청 중 일부는 우리의 권한을 벗어나는 부분이 있습니다. 저희 Billing and Accounts department에서는 기술적인 질문은 다루지 않습니다. 저희는 모든 고객에게 비용 지불의 부담을 주지 않고 저렴한 가격을 유지하기 위해 기술 부문의 Support는 분리해서 다루고 있습니다. 만약 기술적인 support를 원하시면 월 $29 부터 시작되는 Premium Support plan 서비스들이 있습니다. 이 유료 기술 지원 서비스를 이용하시면 이메일, 채팅 그리고 전화등 여러분이 편한 방식으로 엔지니어들과 소통을 할 수 있습니다.

All Premium Support plans include direct access to Support Engineers, and these plans offer a tailored support experience that allows you to select the support level that best fits your needs. More information including pricing and how to sign up can be found here:


모든 Premium Support plan 들에는 Support Engineers과의 직접 access 권한이 포함되며 이러한 플랜들에서는 사용자의 요구 사항에 가장 적합한 서포트 레벨을 선택할 수 있는 맞춤 지원 서비스가 제공 됩니다. 가격 정책 및 가입 방법에 대한 자세한 정보는 여기를 참조하세요.

https://aws.amazon.com/premiumsupport/pricing/ 

You can also search the Amazon Web Services Developer forums or post a new question. Our technical staff and the Amazon Web Services developer community participate in the forums regularly and might be able to help you. Generally, questions are responded to in about a day, though there is not a guaranteed response time.


그 외에  Amazon Web Services Developer forums에서 궁금한 내용을 검색해서 찾는 방법도 있습니다. 또한 새로운 질문을 이곳에 올릴 수도 있구요. Our technical staff와 Amazon Web Services developer community에 참여하는 개발자들로 부터 지원을 받으실 수도 있을 겁니다. 일반적으로 하루 정도 기다리면 답변을 받습니다. (응답 시간에 대한 보장은 없지만요.)

https://forums.aws.amazon.com/index.jspa 

Finally, you may also want to check out our AWS Support Knowledge Center and AWS Documentation pages located here:  

마지막으로 AWS Support Knowledge Center 및 AWS Documentation 페이지를 참조하십시오.

https://aws.amazon.com/premiumsupport/knowledge-center/  
https://aws.amazon.com/documentation/ 

I certainly want you to have the best experience while using our services, so please feel free to let me know if you have any other concern in the meantime, it will be an honor to keep on assisting you. On behalf of Amazon Web Services, I wish you Happy Cloud Computing!

 

Best regards,

Merlyn N.

Amazon Web Services

====================================================================
Learn to work with the AWS Cloud. Get started with free online videos and self-paced labs at 
http://aws.amazon.com/training/ 
====================================================================

Amazon Web Services, Inc. and affiliates

 

 

 

뭐 내용을 읽어보니 어쩔 수 없는 것 같다.

 

어쨌든 한달 정도는 공짜인 것 같으니 거기에 위안을 삼아야지...

 

AWS DeepRacer forum 에 갔더니 나처럼 모델 생성시 Error가 난다는 글이 몇개 눈에 띄었다.

아마도 NAT Gateways를 delete 해서 그런게 아닌지...

 

이 문제 때문인지 몰라도 어제부터 아마존에서 뭔가 이슈를 처리하느라 Training과 evaluation 일을 할 수 없다는 메세지가 뜨더라.

 

 

이 investigation이 위 문제와 관련이 있기를 바라고 또 그 결과로 NAT Gateways 비용 청구와 관련해서 좀 더 전향적인 방안이 제시 됐으면 좋겠다.

 

하루 1불씩 무조건 부과되는건 쫌 부담 스럽다.

내가 필요할 때만 해당 서비스를 사용하고 거기에 대한 비용만 지불할 수 있게 해 달라... 아마존아......

  

반응형


반응형

Hands-on Exercise 1: Model Training Using AWS DeepRacer Console

 

This is the first of four exercises that you will encounter in this course. This first exercise guides you through building, training, and evaluating your first RL model using the AWS DeepRacer console. To access the instructions for three of these exercises, download and unzip this course package. For this particular exercise, find and open the relevant PDF file and follow the steps within to complete the exercise.

*Note: This exercise is designed to be completed in your AWS account. AWS DeepRacer is part of AWS Free Tier, so you can get started at no cost. For the first month after sign-up, you are offered a monthly free tier of 10 hours of Amazon SageMaker training and 60 simulation units of Amazon RoboMaker (enough to cover 10 hours of training). If you go beyond those free tier limits, you will accrue additional costs. For more information, see the AWS DeepRacer Pricing page.

 

Hands-on Exercise 1- Model Training Using AWS DeepRacer Console.pdf
0.23MB

 

 

 

 

Hands-on Exercise 2- Advanced Model Training Using AWS DeepRacer Console.pdf
0.25MB

 

 

For feedback, suggestions, or corrections, email us at aws-course-feedback@amazon.com.

 

 

Hands-on Exercise 3- Distributed AWS DeepRacer RL Training using Amazon SageMaker and AWS RoboMaker.pdf
0.46MB

 

SageMakerForDeepRacerSetup.yaml
0.01MB

 

AWSTemplateFormatVersion: "2010-09-09"
Description: 'AWS DeepRacer: Driven by Reinforcement Learning'
Parameters:
  SagemakerInstanceType:
    Description: 'Machine Learning instance type that should be used for Sagemaker Notebook'
    Type: String
    AllowedValues:
      - ml.t2.medium
      - ml.t2.large
      - ml.t2.xlarge
      - ml.t3.medium
      - ml.t3.large
      - ml.t3.xlarge
      - ml.m5.xlarge
    Default: ml.t3.medium
  CreateS3Bucket:
    Description: Create and use a bucket created via this template for model storage
    Default: True
    Type: String
    AllowedValues:
      - True
      - False
    ConstraintDescription: Must be defined at True|False.
  VPCCIDR:
    Description: 'CIDR Block for VPC (Do Not Edit)'
    Type: String
    Default: 10.96.0.0/16
  PUBSUBNETA:
    Description: 'Public Subnet A (Do Not Edit)'
    Type: String
    Default: 10.96.6.0/24
  PUBSUBNETB:
    Description: 'Public Subnet B (Do Not Edit)'
    Type: String
    Default: 10.96.7.0/24
  PUBSUBNETC:
    Description: 'Public Subnet C (Do Not Edit)'
    Type: String
    Default: 10.96.8.0/24
  PUBSUBNETD:
    Description: 'Public Subnet D (Do Not Edit)'
    Type: String
    Default: 10.96.9.0/24
  S3PathPrefix:
    Type: String
    Description: 'Bootstrap resources prefix'
    Default: 'awsu-spl-dev/spl-227'
  S3ResourceBucket:
    Type: String
    Description: 'Bootstrap S3 Bucket'
    Default: 'aws-training'
Conditions:
  CreateS3Bucket: !Equals [ !Ref CreateS3Bucket, True ]
  #  NoCreateS3Bucket: !Equals [ !Ref CreateS3Bucket, False ]
Resources:

# Defining the VPC Used for the sanbox ENV, and notebook instance
  VPC:
    Type: 'AWS::EC2::VPC'
    Properties:
      CidrBlock: !Ref VPCCIDR
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
      Tags:
        - Key: Name
          Value: 'DeepRacer Sandbox'
# There is a few calls made to public to download supporting resources
  InternetGateway:
    Type: 'AWS::EC2::InternetGateway'
    DependsOn: VPC
    Properties:
      Tags:
        - Key: Name
          Value: 'DeepRacer Sandbox IGW'
# Attached this IGW to the sanbox VPC
  AttachGateway:
    Type: 'AWS::EC2::VPCGatewayAttachment'
    DependsOn:
      - VPC
      - InternetGateway
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway
# Default setting in the notebook is to use Public IP address to communicate
# between instances running the simulation, and the instances collecting and
# processing. A NatGW could have been used with added costs, but would allow for
# use of private IP address.

# Found in testing that not all ML instance types may not be deployed or avaliable
# in all AZ's within a given region. We are using the newest instance family of T3
  PublicSubnetA:
    Type: 'AWS::EC2::Subnet'
    DependsOn: VPC
    Properties:
      VpcId: !Ref VPC
      CidrBlock: !Ref PUBSUBNETA
      AvailabilityZone: !Select
        - '0'
        - !GetAZs ''
      Tags:
        - Key: Name
          Value: 'Deepracer Sandbox - Public Subnet - A'
  PublicSubnetB:
    Type: 'AWS::EC2::Subnet'
    DependsOn: VPC
    Properties:
      VpcId: !Ref VPC
      CidrBlock: !Ref PUBSUBNETB
      AvailabilityZone: !Select
        - '1'
        - !GetAZs ''
      Tags:
        - Key: Name
          Value: 'Deepracer Sandbox Public Subnet - B'
  PublicSubnetC:
    Type: 'AWS::EC2::Subnet'
    DependsOn: VPC
    Properties:
      VpcId: !Ref VPC
      CidrBlock: !Ref PUBSUBNETC
      AvailabilityZone: !Select
        - '2'
        - !GetAZs ''
      Tags:
        - Key: Name
          Value: 'Deepracer Sandbox Public Subnet - C'
  PublicSubnetD:
    Type: 'AWS::EC2::Subnet'
    DependsOn: VPC
    Properties:
      VpcId: !Ref VPC
      CidrBlock: !Ref PUBSUBNETD
      AvailabilityZone: !Select
        - '3'
        - !GetAZs ''
      Tags:
        - Key: Name
          Value: 'Deepracer Sandbox Public Subnet - D'
# Define the Public Routing Table
  PublicRouteTable:
    Type: 'AWS::EC2::RouteTable'
    DependsOn:
      - VPC
      - AttachGateway
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: 'Deepracer Sandbox Public Routing Table'
# And add in the default route to 0.0.0.0/0
  PublicRouteIGW:
    Type: 'AWS::EC2::Route'
    DependsOn:
      - PublicRouteTable
      - InternetGateway
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway
# Attach the routing table to each of the subnets
  PublicRouteTableAssociationA:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref PublicSubnetA
      RouteTableId: !Ref PublicRouteTable
  PublicRouteTableAssociationB:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref PublicSubnetB
      RouteTableId: !Ref PublicRouteTable
  PublicRouteTableAssociationC:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref PublicSubnetC
      RouteTableId: !Ref PublicRouteTable
  PublicRouteTableAssociationD:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref PublicSubnetD
      RouteTableId: !Ref PublicRouteTable
# Define a S3 endpoint for all the S3 traffic during training
  S3Endpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref VPC
      RouteTableIds:
        - !Ref PublicRouteTable
      ServiceName: !Join
        - ''
        - - com.amazonaws.
          - !Ref 'AWS::Region'
          - .s3
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal: '*'
            Action:
              - 's3:*'
            Resource:
              - '*'
# This exercise is going to need a bucket to store any file generated from training
# There is a conditions to evaluate if the PRAM is true, else this resource would
# not be created.
  SandboxBucket:
    Type: 'AWS::S3::Bucket'
    DeletionPolicy: Retain
    Condition: CreateS3Bucket
    Properties:
      BucketName:
        Fn::Join:
          - "-"
          - - deepracer-trainingexercise
            - Ref: AWS::Region
            - Ref: AWS::AccountId
# Sagemaker is going to be making calls to Robomaker to launch the sim, and
# Sagemaker to launch the training insance. This requries AWS credentals. A
# Principal of sagemaker and robomaker needs to be assiged as both service will
# assuming this role. Default Sagemaker full access and s3 access is needed.
  SageMakerNotebookInstanceRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - sagemaker.amazonaws.com
                - robomaker.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/AmazonSageMakerFullAccess'
      Path: /
      Policies:
        - PolicyName: DeepRacerPolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action: [ 's3:*',
                          'iam:GetRole' ]
                Resource: '*'
# This is how the notebook gets loaded on to sagemaker. There is a zip file with
# with the needed files, and a second http call to pull down the notebook.
# This is only done "OnCreate" - when the sagemaker instance is first deployed
# You can can the script get run "OnStart" (when a sagemaker instance changes
# from a stopped state to a running state). This would automaticlly update file
# to be the latest form source, but could over write changes applied during
# your testing
  SageMakerNotebookInstanceLifecycleConfig:
    Type: 'AWS::SageMaker::NotebookInstanceLifecycleConfig'
    Properties:
  #    OnStart:
  #      - Content:
  #          Fn::Base64:
  #            #!/bin/bash
  #            !Sub |
  #            cd SageMaker
  #            chown ec2-user:ec2-user -R /home/ec2-user/SageMaker

      OnCreate:
        - Content:
            Fn::Base64:
              !Sub |
              cd SageMaker
              curl -O https://us-west-2-${S3ResourceBucket}.s3.amazonaws.com/${S3PathPrefix}/scripts/rl_deepracer_robomaker_coach.ipynb
              curl -O https://us-west-2-${S3ResourceBucket}.s3.amazonaws.com/${S3PathPrefix}/scripts/rl_deepracer_robomaker_coach.zip
              unzip rl_deepracer_robomaker_coach.zip
              chown ec2-user:ec2-user -R /home/ec2-user/SageMaker
# Security Group for sagemaker instance running in this VPC
  SagemakerInstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Sagemaker Security Group
      VpcId: !Ref VPC
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: 1
        ToPort: 65535
        CidrIp: !Ref VPCCIDR
      - IpProtocol: udp
        FromPort: 1
        ToPort: 65535
        CidrIp: !Ref VPCCIDR
      SecurityGroupEgress:
      - IpProtocol: tcp
        FromPort: 1
        ToPort: 65535
        CidrIp: !Ref VPCCIDR
      - IpProtocol: udp
        FromPort: 1
        ToPort: 65535
        CidrIp: !Ref VPCCIDR
# Creating the Sagemaker Notebook Instance
  SageMakerNotebookInstance:
    Type: 'AWS::SageMaker::NotebookInstance'
    Properties:
      #NotebookInstanceName: 'DeepracerSagemakerSandbox'
      NotebookInstanceName: !Join ["-", ["DeepRacerSagemakerSandbox", !Ref "AWS::StackName"]]
      SecurityGroupIds:
        - !GetAtt
          - SagemakerInstanceSecurityGroup
          - GroupId
      InstanceType: !Ref SagemakerInstanceType
      SubnetId: !Ref PublicSubnetA
      Tags:
        - Key: Name
          Value: 'DeepRacer Sandbox'
      LifecycleConfigName: !GetAtt
          - SageMakerNotebookInstanceLifecycleConfig
          - NotebookInstanceLifecycleConfigName
      RoleArn: !GetAtt
          - SageMakerNotebookInstanceRole
          - Arn
Outputs:
  # Display the name of the bucekt that was created from this CFN Stack
    ModelBucket:
      Condition: CreateS3Bucket
      Value: !Ref SandboxBucket
  # URL to get to the Sagemaker UI, and find the Jupyter button. 
    SagemakerNotebook:
      Value:
        !Sub |
          https://console.aws.amazon.com/sagemaker/home?region=${AWS::Region}#/notebook-instances/${SageMakerNotebookInstance.NotebookInstanceName}

반응형


반응형

지난 수요일인가 부터 AWS 요금이 꾸준히 부과 되고 있었다.

하루에 1달러가 채 안 되지만 쓰지도 않는데 계속 부과 되서 신경이 쓰였다.

도대체 내가 수요일에 뭘 했길래...

 

그래서 주말에 자세히 살펴 봤다.

 

 

5월 18일 오후 3시 44분. 총액은 5.38달러이다.

 

 

5월 19일 일요일 3시 56분. 거의 24시간 만에 총액은 6.28 달러가 됐다.

Elastic Compute Cloud 를 expand 해서 봤더니 NAT Gateway hour 부분 액수가 증가했다.

 

이제 어디서 부과 되는지 알아냈으니 그걸 de-activate 시키면 될 일.

EC2 - Elastic IPs로 갔더니 NAT Gateway 가 하나 running 중이었다.

 

내가 이걸 수요일에 만들었었나?

전혀 기억이 안나지만 어쨌든 내가 만들었으니 생겼겠지....

 

그래서 그걸 선택하고 Detach를 시도했다.

근데 이런 에러메세지만 나오고 Detach는 거절 당했다.

 

"Error detaching network interface eni--------------: You are not allowed to manage 'ela-attach' attachments."

 

암만 시도해도 안되길래 AWS Support center에 질문을 올렸다.

월요일 아침에 바로 답장이 왔다.

 

 

아마존은 배달만 빠른줄 알았더니 문의에 대한 응답도 1일 배송이었다.

 

Hi there,

I hope you are having a great day.

I understand that you have some charges for NAT Gateway on your AWS account, I'm happy to assist.

1. How can I stop the service?

You can delete a NAT gateway using the Amazon VPC console by following the steps below.

1.  Log into your Amazon VPC console: https://console.aws.amazon.com/vpc/ 
2.  In the navigation pane, choose NAT Gateways.
3.  Select the NAT gateway, and then choose Delete NAT Gateway.
4.  In the confirmation dialog box, choose Delete NAT Gateway.

After you've deleted a NAT gateway, its entry remains visible in the Amazon VPC console for a short while (usually an hour), after which it's automatically removed. You cannot remove this entry yourself.

More information on NAT Gateway can be found here:

https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html 

It's important to note that deleting a NAT gateway disassociates its Elastic IP address, but does not release that Elastic IP address from your AWS account. You will incur charges for any Elastic IP address that remains allocated to your account, but is not associated with an instance.

We recommend you release a disassociated Elastic IP address from your account if you no longer need it. To release an Elastic IP address:

1.  Open the Amazon VPC console at: https://console.aws.amazon.com/vpc/ .
2.  In the navigation panel, choose Elastic IPs.
3.  Select the Elastic IP address you wish to release, choose Actions, and then choose Release addresses.
4.  When prompted, choose Release.

To learn more about Elastic IP addresses, please follow the link below:

http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-eips.html 

2. When (and How) did I created the service?  (I don't remember when and how I created it.

After reviewing your AWS account, I could see that this Nat Gateway was created on May 15, 2019. I've added a report so you can see that the charges started on May 15th.

We do not have the information on how it was created but this documentation can be helpful to you.

https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html#nat-gateway-creating 

I hope this information helps, but please let us know if you need any additional assistance.

To see the file named 'Nat Gateway.xlsx' included with this correspondence, please use the case link given below the signature.

Best regards,

Mariano S.
Amazon Web Services

Check out the AWS Support Knowledge Center, a knowledge base of articles and videos that answer customer questions about AWS services: https://aws.amazon.com/premiumsupport/knowledge-center/?icmpid=support_email_category 

We value your feedback. Please rate my response using the link below.
===================================================

To contact us again about this case, please return to the AWS Support Center using the following URL:

https://console.aws.amazon.com/support/home#/case/?displayId=6086834221&language=en 

(If you are connecting by federation, log in before following the link.)

*Please note: this e-mail was sent from an address that cannot accept incoming e-mail. Please use the link above if you need to contact us again about this same issue.

====================================================================
Learn to work with the AWS Cloud. Get started with free online videos and self-paced labs at 
http://aws.amazon.com/training/ 
====================================================================

Amazon Web Services, Inc. and affiliates

 

 



봤더니 NAT Gateway는 EC2가 아니라 VPC로 가서 Delete를 해 줘야 하는 거였다.

VPC - NAT Gateways - 선택 후 Delete

 

간단했다.

 

메일에서 추천한대로 Elastics IPs 로 가서 해당 Elastic IP address를 release 했다.

 

이걸로 사용도 하지 않는 Paid AWS Service 때문에 요금이 부과 되는 상황은 중지 시킨거 같다.

내일 확실히 확인해 봐야지.

 

지난주 시작했던 DeepRacer 공부나 계속 이어가야 겠다.

 

 

 

반응형


반응형

Introduction to reinforcement learning

 

Developers, start your engines!

This guide will walk you through the basics of reinforcement learning (RL), how to train an RL model, and define the reward functions with parameters.

With this knowledge, you’ll be ready to race in the 2019 AWS DeepRacer League.

 

 

https://d2k9g1efyej86q.cloudfront.net/

 

Introduction to Reinforcement Learning

 

d2k9g1efyej86q.cloudfront.net

 

(RL)Reinforcement learning (RL)은 기계 학습 machine learning의 한 유형으로, agent가 원하는 임무를 어떻게 수행할 것인가를 배우기 위해 주어진 환경environment 을 탐구하는 것입니다. 좋은 결과를 위한 액션을 취하고 나쁜 결과를 초래하는 액션은 회피함으로서 원하는 임무에 최적화 된 행동을 학습하게 됩니다.  

reinforcement learning 모델은 경험을 통해 배우며 시간이 지남에 따라 어떤 행동이 최상의 보상reward으로 이어질지 식별 할 수 있게 됩니다.

 

다른 타입의 machine learning

 

Supervised learning

예제 중심 교육 - 주어진 입력들에 대해 알려진 출력들에 대한 레이블된 데이터를 가지고 이 모델은 새로운 입력에 대한 출력을 예측하도록 훈련됩니다. 

 

Unsupervised learning

추론 기반 교육 - 알려진 출력이 없는 레이블된 데이터를 가지고 이  모델은 입력 데이터 내의 관련 구조 또는 유사한 패턴을 식별하도록 훈련됩니다.

 

How does AWS DeepRacer learn to drive by itself?

 

In reinforcement learning, an agent interacts with an environment with an objective to maximize its total reward.

The agent takes an action based on the environment state and the environment returns the reward and the next state. The agent learns from trial and error, initially taking random actions and over time identifying the actions that lead to long-term rewards.

Let's explore these ideas and how they relate to AWS DeepRacer.

 

reinforcement learning에서 agent 는 환경environment 과 상호 작용하여 총 보상reward을 최대화합니다.

agent 는 환경environment  상태state 에 따라 조치를 취하고 환경environment  은 보상reward과 다음 상태state 를 반환합니다. 에이전트agent 는 초기에 무작위로 행동을 취하고 시간이 지남에 따라 장기 보상long-term rewards으로 이어지는 행동을 식별함으로써 이러한 시행 착오를 통해 학습합니다.

이런 각각의 개념들을 살펴보고 AWS DeepRacer와의 관계에 대해서도 알아보겠습니다.

Agent

The agent simulates the AWS DeepRacer vehicle in the simulation for training. More specifically, it embodies the neural network that controls the vehicle, taking inputs and deciding actions.

 

에이전트agent 는 훈련을 하기 위해 시뮬레이션에서 AWS DeepRacer 차량을 시뮬레이트 합니다. 보다 구체적으로, 차량을 제어하고 입력을 취하고 행동을 결정하는 신경망을 구현합니다.

 

Environment

The environment contains a track that defines where the agent can go and what state it can be in. The agent explores the envrionment to collect data to train the underlying neural network.

 

환경environment 은 에이전트agent 가 어디로 갈 수 있고 어떤 상태에 놓일 수 있는 지에 대해 정의하는 트랙으로 구성됩니다.  에이전트는 기본 신경 네트워크를 훈련하기 위해 주어진 환경(트랙)을 탐색하면서 데이터를 수집합니다.

 

State

A state represents a snapshot of the environment the agent is in at a point in time.

For AWS DeepRacer, a state is an image captured by the front-facing camera on the vehicle.

 

상태state 는 특정 시점에 에이전트가있는 환경의 스냅 샷을 가리킵니다.
AWS DeepRacer의 경우 상태는 차량의 전면 카메라가 캡처 한 이미지입니다.

 

Action

An action is a move made by the agent in the current state. For AWS DeepRacer, an action corresponds to a move at a particular speed and steering angle.

 

동작action 은 현재 상태에서 agent가 수행 한 동작입니다. AWS DeepRacer의 경우 동작은 특정 속도 및 방향(핸들) 각도 등의 움직임과 관계된 액션을 말합니다. 

 

Reward

The reward is the score given as feedback to the agent when it takes an action in a given state.

In training the AWS DeepRacer model, the reward is returned by a reward function. In general, you define or supply a reward function to specify what is desirable or undesirable action for the agent to take in a given state.

 

보상reward은 어떤 주어진 상태에서 action를 취했을 때 agent 에게 피드백으로 주어지는 점수입니다.

AWS DeepRacer 모델을 교육 할 때 보상reward reward function에 의해 반환됩니다. 일반적으로 agent 가 주어진 상태에서 취할 수있는 바람직하거나 바람직하지 않은 작업을 지정하기 위해 보상 기능을 정의하거나 제공합니다.

 

 

 

훈련은 반복적 인 과정입니다. 시뮬레이터에서 에이전트는 환경을 탐색하고 경험을 쌓습니다. 수집 된 경험은 신경망을 주기적으로 업데이트하는 데 사용되며 업데이트 된 모델은 더 많은 경험을 생성하는 데 사용됩니다.

 

AWS DeepRacer를 사용하여 자율 운전을 위한 차량을 교육합니다. 교육 과정을 시각화하는 것이 까다로울 수 있으므로 간단한 예를 살펴 보겠습니다.

 

 

이 예에서는 출발점에서 결승점까지 차량이 최단 경로로 갈 수 있도록 훈련시키려고 합니다.

 

우리는 환경environment 을 사각형 격자로 단순화했습니다. 각 사각형은 개별 상태를 나타내며, 목표 방향으로 차량을 위 또는 아래로 움직일 수 있습니다.

 

 

grid 내의 각 격자(사각형)마다 점수를 할당 할 수 있습니다. 그럼으로서 어떤 행동에 인센티브를 줄지 결정할 수 있게 됩니다. 

 

여기서 우리는 트랙의 가장자리에있는 사각형들을 "정지 상태 stop states"로 지정하여 차량이 트랙에서 벗어 났음을 알립니다.

 

우리가 트랙의 중심을 주행하는 법을 배울 수 있게 하도록 차량에 인센티브를 부여하기를 원하기 때문에 센터 라인의 사각형에 높은 보상reward 을 설정하고 다른 곳에는 보다 낮은 보상reward 을 설정합니다.

 

An episode

In reinforcement training, the vehicle will start by exploring the grid until it moves out of bounds or reaches the destination.

 

As it drives around, the vehicle accumulates rewards from the scores we defined. This process is called an episode.

In this episode, the vehicle accumulates a total reward of 2.2 before reaching a stop state.

 

reinforcement training은 여기서 차량이 grid 를 탐색하기 시작하여 경계를 벗어나거나 목적지까지 도달하면 일단락 하게 됩니다.

 

차량이 움직이게 되면 우리가 지정한 점수에 따라 rewards 가 점점 쌓이게 됩니다. 이러한 과정을 에피소드라고 합니다. 위 에피소드에서 이 차량이 stop state에 도달하기 까지 총 2.2 점의 reward 를 쌓았습니다.  

 

Iteration

Reinforcement learning algorithms are trained by repeated optimization of cumulative rewards.

 

Reinforcement learning algorithms은 누적된 rewards를 최적화 (최대화) 하기 위해 반복해서 훈련하게 됩니다.

 

The model will learn which action (and then subsequent actions) will result in the highest cumulative reward on the way to the goal.

 

이 모델은 우리가 목표로 하는 것을 달성하기 위한 최대화된 누적보상의 결과를 가져 올 수 있게 하는 것이 어떤 행동 (그리고 후속 행동)인가를 배우게 됩니다. 

 

Learning doesn’t just happen on the first go; it takes some iteration. First, the agent needs to explore and see where it can get the highest rewards, before it can exploit that knowledge.

 

학습은 한번에 완성되지 않습니다. 반복이 필요합니다. 첫째, 에이전트는 knowledge를 취하기 전에 가장 높은 보상을 받을 수 있는 것이 어떤 것인지를 탐색해야 합니다. 

 

Exploration

As the agent gains more and more experience, it learns to stay on the central squares to get higher rewards.

If we plot the total reward from each episode, we can see how the model performs and improves over time.

 

agent 는 점점 더 많은 경험을 쌓게 됩니다. 그러는 와중에 더 많은 점수를 얻으려면 중앙 격자를 계속 따라가야 한다는 것을 배우게 될 것입니다. 

 

각 에피소드별 보상 점수가 어떤지를 보면 이 모델이 어떤 퍼포먼스를 보여주고 있고 얼마나 개선되고 있는지를 알 수 있습니다.

Exploitation and Convergence

With more experience, the agent gets better and eventually is able to reach the destination reliably.

 

경험이 많아질 수록 agent 는 점점 더 나아지고 결국에는 목표에 도달할 수 있게 됩니다.

 

Depending on the exploration-exploitation strategy, the vehicle may still have a small probability of taking random actions to explore the environment.

 

이 exploration-exploitation strategy(탐사-탐사 전략)에 근거해서 차량은 환경을 탐사하기 위한 랜덤한 액션 (무작위 행동)을 할 가능성이 점점 더 줄어들게 됩니다.

 

 

 

AWS DeepRacer에서 보상 기능 reward function은 현재 상태를 설명하고 숫자 보상 값을 반환하는 특정 매개 변수가있는 Python 함수입니다.

 

보상 기능으로 전달 된 매개 변수는 트랙의 위치와 방향, 관측 된 속도, 조향 각도 등과 같은 차량 상태의 다양한 측면을 나타냅니다.

 

우리는이 매개 변수 중 몇 가지를 탐색하고 트랙 주변을 따라 차량을 묘사하는 방법을 살펴 보겠습니다.

 

  • Position on track
  • Heading
  • Waypoints
  • Track width
  • Distance from center line
  • All wheels on track
  • Speed
  • Steering angle

1. Position on track

The parameters x and y describe the position of the vehicle in meters, measured from the lower-left corner of the environment.

 

매개 변수 x 및 y는 환경의 왼쪽 하단 모서리에서 측정 한 차량의 위치를 미터 단위로 나타냅니다.

 

 

2. Heading

The heading parameter describes the orientation of the vehicle in degrees, measured counter-clockwise from the X-axis of the coordinate system.

 

heading 매개 변수는 좌표계의 X 축에서 시계 반대 방향으로 측정 한 차량의 방향을 도 단위로 나타냅니다.

 

 

3. Waypoints

The waypoints parameter is an ordered list of milestones placed along the track center.

Each waypoint in waypoints is a pair [x, y] of coordinates in meters, measured in the same coordinate system as the car's position.

 

waypoints 매개 변수는 트랙 센터를 따라 배치 된 마일스톤의 정렬 된 목록입니다.
waypoints 안에있는 각 waypoints 는  자동차의 위치에 대해 좌표계에서 측정 된 미터 단위의 좌표 [x, y] 쌍입니다.

 

 

4. Track width

The track_width parameter is the width of the track in meters.

 

track_width parameter는 미터로 된 트랙의 너비 입니다.

 

 

5. Distance from center line

The distance_from_center parameter measures the displacement of the vehicle from the center of the track.

The is_left_of_center parameter is a boolean describing whether the vehicle is to the left of the center line of the track.

 

distance_from_center 매개 변수는 트랙의 중심에서 차량의 변위를 측정합니다.
is_left_of_center 매개 변수는 차량이 트랙의 중심선 왼쪽에 있는지 여부를 나타내는 boolean  값입니다.

 

 

6. All wheels on track

The all_wheels_on_track parameter is a boolean (true / false) which is true if all four wheels of the vehicle are inside the track borders, and false if any wheel is outside the track.

 

all_wheels_on_track 매개 변수는 boolean  (true / false)이며 차량의 네 바퀴가 모두 트랙 테두리 안에 있으면 true이고, 하나라도 바퀴가 밖에 있으면 false가 됩니다.

 

 

7. Speed

The speed parameter measures the observed speed of the vehicle, measured in meters per second.

 

speed parameter는 초속 몇미터인가를 나타내는 차량의 관측된 속도입니다.

 

 

8. Steering angle

The steering_angle parameter measures the steering angle of the vehicle, measured in degrees.

This value is negative if the vehicle is steering right, and positive if the vehicle is steering left.

 

steering_angle 매개 변수는 차량의 조향 각도를 도 단위로 측정합니다.
이 값은 차량이 오른쪽으로 조향하는 경우 음수이고 차량이 좌회전하는 경우 양수입니다.

 

 

read the detailed documentation

 

Train and Evaluate AWS DeepRacer Models Using the AWS DeepRacer Console - AWS DeepRacer

Train and Evaluate AWS DeepRacer Models Using the AWS DeepRacer Console To train a reinforcement learning model, you can use the AWS DeepRacer console. In the console, create a training job, choose a supported framework and an available algorithm, add a re

docs.aws.amazon.com

 

 

The Reward Function.

 

Putting it all together

With all these parameters at your disposal, you can define a reward function to incentivize whatever driving behavior you like.

Let's see a few examples of reward functions and how they use the parameters to determine a reward. The following three reward functions are available as examples in the AWS DeepRacer console so you can try them out and see how they behave, or submit them to the AWS DeepRacer League.

 

이러한 모든 매개 변수를 마음대로 활용하면 원하는 운전 행동에 대한 인센티브를 주는 보상 기능을 정의 할 수 있습니다.

보상 기능의 몇 가지 예와 보상을 결정하기 위해 매개 변수를 사용하는 방법을 살펴 보겠습니다. AWS DeepRacer 콘솔에서 다음과 같은 세 가지 보상 기능을 사용할 수 있으므로 이를 시험해보고 어떻게 동작하는지 보거나 AWS DeepRacer League에 제출할 수 있습니다.

 

 

이 예에서는 자동차가 궤도에 머무를 때 높은 보상을주고 차가 궤도 경계를 벗어나는 경우 페널티를줍니다.

이 예제에서는 all_wheels_on_track, distance_from_center 및 track_width 매개 변수를 사용하여 자동차가 트랙에 있는지 여부를 확인하고 높은 경우 보상을 제공합니다.

이 기능은 트랙에 머무르는 것 이외의 특정 종류의 행동에 대해 보상하지 않으므로이 기능으로 교육받은 agent 는 특정 행동으로 수렴하는 데 시간이 오래 걸릴 수 있습니다.

 

 

 

 

이 예제에서 우리는 트랙의 중심에서 차가 얼마나 떨어져 있는지 측정하고, 차가 중심선에 가까이 있으면 더 높은 보상을줍니다.

이 예제에서는 track_width 및 distance_from_center 매개 변수를 사용하고 트랙의 중심에서 차가 멀어 질수록 보상이 줄어 듭니다.

이 예는 보상의 대상이되는 운전 행동의 유형에 따라 다르므로이 기능을 사용하여 교육을받은 agent는 트랙을 잘 따라갈 수 있습니다. 그러나 모서리의 가속이나 제동과 같은 다른 행동을 배우기는 쉽지 않습니다.

 

 

 

대안의 전략 alternative strategy은 자동차가 운전하는 방식에 관계없이 각 단계에 대해 지속적인 보상을 제공하는 것입니다.

이 예제는 입력 매개 변수를 사용하지 않고 각 단계마다 상수 보상 1.0을 반환합니다.

에이전트의 유일한 인센티브는 트랙을 성공적으로 끝내는 것이고, 더 빠르게 운전하거나 특정 경로를 따라갈 인센티브가 없습니다. 그것은 불규칙하게 행동 할 수 있습니다.

그러나 보상 기능은 agent의 행동을 제한하지 않으므로 예상치 못한 전략과 행동을 탐색하여 오히려 실적이 좋을 수도 있습니다.

 

 

 

 

 

 

반응형


반응형

 

 

1. https://matplotlib.org/api/_as_gen/matplotlib.pyplot.html

 

matplotlib.pyplot — Matplotlib 3.0.3 documentation

matplotlib.pyplot matplotlib.pyplot is a state-based interface to matplotlib. It provides a MATLAB-like way of plotting. pyplot is mainly intended for interactive plots and simple cases of programmatic plot generation: import numpy as np import matplotlib.

matplotlib.org

matplotlib.pyplot

matplotlib.pyplot is a state-based interface to matplotlib. It provides a MATLAB-like way of plotting.

pyplot is mainly intended for interactive plots and simple cases of programmatic plot generation:

import numpy as np

import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)

y = np.sin(x)

plt.plot(x, y)

The object-oriented API is recommended for more complex plots.

 

2. 함수

3. 위 함수 실행

4. 위 함수 실행

5. https://www.tutorialspoint.com/python_pandas/python_pandas_series.htm

 

Python Pandas Series

Python Pandas - Series Advertisements Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). The axis labels are collectively called index. pandas.Series A pandas Series can be created

www.tutorialspoint.com

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html

 

pandas.Series.map — pandas 0.24.2 documentation

Parameters: arg : function, dict, or Series Mapping correspondence. na_action : {None, ‘ignore’}, default None If ‘ignore’, propagate NaN values, without passing them to the mapping correspondence.

pandas.pydata.org

https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html

 

numpy.random.randn — NumPy v1.16 Manual

Parameters: d0, d1, …, dn : int, optional The dimensions of the returned array, should be all positive. If no argument is given a single Python float is returned.

docs.scipy.org

8. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html

 

pandas.DataFrame.corr — pandas 0.24.2 documentation

Parameters: method : {‘pearson’, ‘kendall’, ‘spearman’} or callable pearson : standard correlation coefficient kendall : Kendall Tau correlation coefficient spearman : Spearman rank correlation callable: callable with input two 1d ndarrays and returning a

pandas.pydata.org

9. https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html

 

matplotlib.pyplot.scatter — Matplotlib 3.0.3 documentation

Parameters: x, y : array_like, shape (n, ) The data positions. s : scalar or array_like, shape (n, ), optional The marker size in points**2. Default is rcParams['lines.markersize'] ** 2. c : color, sequence, or sequence of color, optional The marker color.

matplotlib.org

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.grid.html?highlight=grid#matplotlib.pyplot.grid

 

matplotlib.pyplot.grid — Matplotlib 3.0.3 documentation

Parameters: b : bool or None Whether to show the grid lines. If any kwargs are supplied, it is assumed you want the grid on and b will be set to True. If b is None and there are no kwargs, this toggles the visibility of the lines. which : {'major', 'minor'

matplotlib.org

https://matplotlib.org/api/legend_api.html?highlight=legend#module-matplotlib.legend

 

legend and legend_handler — Matplotlib 3.0.3 documentation

Other Parameters: loc : int or string or pair of floats, default: rcParams["legend.loc"] ('best' for axes, 'upper right' for figures) The location of the legend. Possible codes are: Location String Location Code 'best' 0 'upper right' 1 'upper left' 2 'low

matplotlib.org

11. https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html

 

numpy.random.shuffle — NumPy v1.16 Manual

Modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same. Parameters: x : array_like The array or l

docs.scipy.org

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html

 

pandas.DataFrame.iloc — pandas 0.24.2 documentation

Purely integer-location based indexing for selection by position. .iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array. Allowed inputs are: An integer, e.g. 5. A list or array of integers,

pandas.pydata.org

 

 

1. Install XGBOOST https://github.com/conda-forge/xgboost-feedstock

 

conda-forge/xgboost-feedstock

A conda-smithy repository for xgboost. Contribute to conda-forge/xgboost-feedstock development by creating an account on GitHub.

github.com

 

 

 

3. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html?highlight=read_csv#pandas.read_csv

 

pandas.read_csv — pandas 0.24.2 documentation

Parameters: filepath_or_buffer : str, path object, or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: file://local

pandas.pydata.org

 

 

 

 

 

 

12. https://xgboost.readthedocs.io/en/latest/python/python_api.html

 

Python API Reference — xgboost 0.83.dev0 documentation

Python API Reference This page gives the Python API reference of xgboost, please also refer to Python Package Introduction for more information about python package. Core Data Structure Core XGBoost Library. class xgboost.DMatrix(data, label=None, missing=

xgboost.readthedocs.io

 

 

20. 

Plotting API

Plotting Library.

xgboost.plot_importance(booster, ax=None, height=0.2, xlim=None, ylim=None, title='Feature importance', xlabel='F score', ylabel='Features', importance_type='weight', max_num_features=None, grid=True, show_values=True, **kwargs)

Plot importance based on fitted trees.

 

25. predict(data, output_margin=False, ntree_limit=0, pred_leaf=False, pred_contribs=False, approx_contribs=False, pred_interactions=False, validate_features=True)

Predict with data.

Note

This function is not thread safe.

For each booster object, predict can only be called from one thread. If you want to run prediction using multiple thread, call bst.copy() to make copies of model object and then call predict().

Note

Using predict() with DART booster

If the booster object is DART type, predict() will perform dropouts, i.e. only some of the trees will be evaluated. This will produce incorrect results if data is not the training data. To obtain correct results on test sets, set ntree_limit to a nonzero value, e.g.

preds = bst.predict(dtest, ntree_limit=num_round)

30. https://matplotlib.org/api/_as_gen/matplotlib.pyplot.boxplot.html

 

matplotlib.pyplot.boxplot — Matplotlib 3.0.3 documentation

Parameters: x : Array or a sequence of vectors. The input data. notch : bool, optional (False) If True, will produce a notched box plot. Otherwise, a rectangular boxplot is produced. The notches represent the confidence interval (CI) around the median. See

matplotlib.org

31. https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html

 

matplotlib.pyplot.hist — Matplotlib 3.0.3 documentation

Parameters: x : (n,) array or sequence of (n,) arrays Input values, this takes either a single array or a sequence of arrays which are not required to be of the same length. bins : int or sequence or str, optional If an integer is given, bins + 1 bin edges

matplotlib.org

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.axvline.html

 

matplotlib.pyplot.axvline — Matplotlib 3.0.3 documentation

Parameters: x : scalar, optional, default: 0 x position in data coordinates of the vertical line. ymin : scalar, optional, default: 0 Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot. ymax : scalar, optional, default: 1 Shou

matplotlib.org

 

37. https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.describe.html

 

pandas.DataFrame.describe — pandas 0.21.1 documentation

percentiles : list-like of numbers, optional The percentiles to include in the output. All should fall between 0 and 1. The default is [.25, .5, .75], which returns the 25th, 50th, and 75th percentiles. include : ‘all’, list-like of dtypes or None (default

pandas.pydata.org

 

반응형