20 Examples to Master Pandas Series -번역

판다 시리즈를 마스터하기위한 20 가지 예

Pandas의 핵심 데이터 구조

Photo by Yannis Zaugg on Unsplash

Pandas는 Python을위한 매우 인기있는 데이터 분석 및 조작 라이브러리입니다.데이터를 표 형식으로 처리 할 수있는 다양하고 강력한 기능을 제공합니다.

Pandas의 두 가지 핵심 데이터 구조는 DataFrame과 Series입니다.DataFrame은 레이블이있는 행과 열이있는 2 차원 구조입니다.SQL 테이블과 유사합니다.시리즈는 레이블이 지정된 1 차원 배열입니다.시리즈의 값 레이블을 인덱스라고합니다.DataFrame과 Series는 모든 데이터 유형을 저장할 수 있습니다.

이 기사에서는 시리즈에서 수행 할 수있는 다양한 작업을 보여주는 20 개의 예제를 살펴 보겠습니다.

먼저 라이브러리를 가져온 다음 예제부터 시작하겠습니다.

numpy를 np로 가져 오기
팬더를 pd로 가져 오기

1. DataFrame is composed of Series

DataFrame의 개별 행 또는 열은 시리즈입니다.

왼쪽의 DataFrame을 고려하십시오.특정 행이나 열을 선택하면 반환되는 데이터 구조는 시리즈입니다.

a = df.iloc [0, :]
인쇄 (유형 (a))
pandas.core.series.Series
b = df [0]
유형 (b)
pandas.core.series.Series

2. Series consists of values and index

시리즈는 레이블이있는 배열입니다.인덱스라고하는 값과 레이블에 액세스 할 수 있습니다.

ser = pd.Series ([ 'a', 'b', 'c', 'd', 'e'])print (ser.index)
RangeIndex (시작 = 0, 중지 = 5, 단계 = 1)
print (ser.values)
['에이 비 씨 디이']

3. Index can be customized

이전 예에서 볼 수 있듯이 0부터 시작하는 정수 인덱스는 기본적으로 Series에 할당됩니다.그러나 index 매개 변수를 사용하여 변경할 수 있습니다.

ser = pd.Series ([ 'a', 'b', 'c', 'd', 'e'], 인덱스 = [10,20,30,40,50])print (ser.index)
Int64Index ([10, 20, 30, 40, 50], dtype = 'int64')

4. Series from a list

우리는 이미 이전 예제에서 이것을 보았습니다.목록을 Series 함수에 전달하여 Series를 만들 수 있습니다.

list_a = [ '데이터', '과학', '기계', '학습']ser = pd.Series (list_a)유형 (ser)
pandas.core.series.Series

5. Series from a NumPy array

시리즈를 만드는 또 다른 일반적인 방법은 NumPy 배열을 사용하는 것입니다.목록에서 만드는 것과 같습니다.Series 함수에 전달 된 데이터 만 변경합니다.

arr = np.random.randint (0, 10, 크기 = 50)ser = pd.Series (arr)

6. Accessing individual values

시리즈에는 레이블이 지정된 항목이 포함되어 있으므로 레이블 (즉, 색인)을 사용하여 특정 항목에 액세스 할 수 있습니다.

ser = pd.Series ([ 'a', 'b', 'c', 'd', 'e'])인쇄 (ser [0])
인쇄 (ser [2])

7. Slicing a Series

인덱스를 사용하여 Series를 분할 할 수도 있습니다.

ser = pd.Series ([ 'a', 'b', 'c', 'd', 'e'])print (ser [: 3])
0 a
1b
2 개 c
dtype : 개체
print (ser [2 :])
2 개 c
3 일
4 e
dtype : 개체

8. Data types

Pandas는 Series를 만들 때 적절한 데이터 유형을 할당합니다.dtype 매개 변수를 사용하여 변경할 수 있습니다.물론 적절한 데이터 유형을 선택해야합니다.

ser1 = pd.Series ([1,2,3,4,5])
인쇄 (ser1)
0 1
1 2
2 3
3 4
4 5
dtype : int64
ser2 = pd.Series ([1,2,3,4,5], dtype = 'float')
0 1.0
1 2.0
2 3.0
3 4.0
4 5.0
dtype : float64

9. Number of items in a Series

시리즈의 값 수를 계산하는 방법에는 여러 가지가 있습니다.컬렉션이기 때문에 파이썬에 내장 된 len 함수를 사용할 수 있습니다.

ser = pd.Series ([1,2,3,4,5])len (ser)
5

Pandas의 크기 및 모양 기능을 사용할 수도 있습니다.

ser.size
5
ser.shape
(5,)

shape 함수는 각 차원의 크기를 반환합니다.Series는 1 차원이므로 shape 함수에서 길이를 얻습니다.Size는 Series 또는 DataFrame의 전체 크기를 반환합니다.DataFrame에서 사용되는 경우 size는 행과 열 수의 곱을 반환합니다.

10. 독특하고 Nunique

unique 및 nunique 함수는 각각 고유 값과 고유 값 수를 반환합니다.

ser = pd.Series ([ 'a', 'a', 'a', 'b', 'b', 'c'])ser.unique ()
배열 ([ 'a', 'b', 'c'], dtype = object)
ser.nunique ()

11. Largest and smallest values

nlargest 및 nsmallest 함수는 Series에서 가장 큰 값과 가장 작은 값을 반환합니다.기본적으로 5 개의 가장 큰 값 또는 가장 작은 값을 얻지 만 n 매개 변수를 사용하여 변경할 수 있습니다.

ser = pd.Series (np.random.random (size = 500))ser.nlargest (n = 3)
292 0.997681
236 0.997140
490 0.996117
dtype : float64
ser.nsmallest (n = 2)
157 0.001499
140 0.002313
dtype : float64

12. Series from a dictionary

시리즈 함수에 사전을 전달하면 반환 된 시리즈에는 사전 값이 포함됩니다.색인은 사전의 키입니다.

dict_a = { 'a': 1, 'b': 2, 'c': 8, 'd': 5}pd. 시리즈 (dict_a)
a 1
b 2
c 8
d 5
dtype : int64

13. Converting data type

시리즈를 생성 할 때 데이터 유형을 선택할 수있는 옵션이 있습니다.Pandas는 나중에 데이터 유형을 변경할 수도 있습니다.

예를 들어, 다음 시리즈는 정수를 포함하지만 dtype 객체로 저장됩니다.astype 함수를 사용하여 정수로 변환 할 수 있습니다.

ser = pd.Series ([ '1', '2', '3', '4'])ser
0 1
1 2
2 3
3 4
dtype : 개체
ser.astype ( 'int')
0 1
1 2
2 3
3 4
dtype : int64

14. Number of occurrences of values

value_counts 함수는 Series에서 각 고유 값의 발생 횟수를 반환합니다.값 분포에 대한 개요를 얻는 것이 유용합니다.

ser = pd.Series ([ 'a', 'a', 'a', 'b', 'b', 'c'])ser.value_counts ()
3
b 2
c 1
dtype : int64

15. From series to list

목록에서 시리즈를 만들 수있는 것처럼 시리즈를 목록으로 변환 할 수 있습니다.

ser = pd.Series (np.random.randint (10, 크기 = 10))ser.to_list ()
[8, 9, 0, 0, 7, 1, 8, 6, 0, 8]

16. Null values

시리즈에 누락 된 값이있을 가능성이 있습니다.Pandas를 사용하면 누락 된 값을 감지하고 처리하는 것이 매우 간단합니다.

예를 들어, count 함수는 계열에서 결 측값이 아닌 값의 수를 반환합니다.

ser = pd.Series ([1, 2, 3, np.nan, np.nan])ser.count ()

17. Null values — 2

결 측값을 감지하는 또 다른 방법은 isna 함수입니다.True로 누락 된 값을 나타내는 부울 값이있는 Series를 반환합니다.

ser = pd.Series ([1, 2, 3, np.nan, np.nan])ser.isna ()
0 거짓
1 거짓
2 거짓
3 참
4 참
dtype : 부울

합계 함수를 isna 함수와 연결하여 누락 된 값의 수를 계산할 수 있습니다.

ser.isna (). sum ()
2

18. Rounding up floating point numbers

데이터 분석에서 우리는 숫자 값을 가질 가능성이 가장 높습니다.Pandas는 숫자 데이터를 조작 할 수있는 능력이 뛰어납니다.예를 들어, round 함수를 사용하면 부동 소수점 숫자를 특정 소수점까지 반올림 할 수 있습니다.

다음 시리즈를 고려하십시오.

ser
0 0.349425
1 0.552831
2 0.104823
3 0.899308
4 0.825984
dtype : float64

round 함수가 사용되는 방법은 다음과 같습니다.

ser.round (2)
0 0.35
1 0.55
2 0.10
3 0.90
4 0.83
dtype : float64

19. Logical operators

같음, 작음 또는보다 큼과 같은 논리 연산자를 Series에 적용 할 수 있습니다.True로 지정된 조건에 맞는 값을 나타내는 부울 값이있는 Series를 반환합니다.

ser = pd.Series ([1, 2, 3, 4])ser.eq (3)
0 거짓
1 거짓
2 참
3 거짓
dtype : 부울
ser.gt (2)
0 거짓
1 거짓
2 참
3 참
dtype : 부울

논리 연산자의 전체 목록 :

  • lt : 이하
  • le : 작거나 같음
  • gt :보다 큼
  • ge : 크거나 같음
  • eq : 같음
  • ne : 같지 않음

20. 데이터 집계

평균, 합계, 중앙값 등과 같은 집계 함수를 시리즈에 적용 할 수 있습니다.시리즈에 별도로 적용하는 한 가지 방법입니다.

ser = pd.Series ([1, 2, 3, 4, 10])ser.mean ()
4

여러 집계 함수를 적용해야하는 경우 더 나은 방법이 있습니다.목록에서 agg 함수에 전달할 수 있습니다.

ser.agg ([ '평균', 'median', 'sum', 'count'])평균 4.0
중앙값 3.0
합계 20.0
카운트 5.0
dtype : float64

Conclusion

우리는 Series의 속성과 그것과 상호 작용하는 기능을 보여주는 20 개의 예제를 만들었습니다.DataFrame은 Series로 구성되어 있으므로 DataFrame만큼 중요합니다.

이 기사의 예제는 Series에서 일반적으로 사용되는 많은 데이터 작업을 다룹니다.물론 시리즈에서 사용할 수있는 더 많은 기능과 방법이 있습니다.필요에 따라 더 고급 또는 세부 작업을 배울 수 있습니다.

읽어 주셔서 감사합니다.의견이 있으면 알려주세요.

20 Examples to Master Pandas Series

20 Examples to Master Pandas Series

A core data structure of Pandas

Photo by Yannis Zaugg on Unsplash

Pandas is a highly popular data analysis and manipulation library for Python. It provides versatile and powerful functions to handle data in tabular form.

The two core data structures of Pandas are DataFrame and Series. DataFrame is a two-dimensional structure with labelled rows and columns. It is similar to a SQL table. Series is a one-dimensional labelled array. The labels of values in a Series are referred to as index. Both DataFrame and Series are able to store any data type.

In this article, we will go through 20 examples that demonstrate various operations we can perform on a Series.

Let’s first import the libraries and then start with the examples.

import numpy as np
import pandas as pd

1. DataFrame is composed of Series

An individual row or column of a DataFrame is a Series.

Consider the DataFrame on the left. If we select a particular row or column, the returned data structure is a Series.

a = df.iloc[0, :]
print(type(a))
pandas.core.series.Series
b = df[0]
type(b)
pandas.core.series.Series

2. Series consists of values and index

Series is a labelled array. We can access the values and labels which are referred to as index.

ser = pd.Series(['a','b','c','d','e'])print(ser.index)
RangeIndex(start=0, stop=5, step=1)
print(ser.values)
['a' 'b' 'c' 'd' 'e']

3. Index can be customized

As we see in the previous example, an integer index starting from zero are assigned to a Series by default. However, we can change it using the index parameter.

ser = pd.Series(['a','b','c','d','e'], index=[10,20,30,40,50])print(ser.index)
Int64Index([10, 20, 30, 40, 50], dtype='int64')

4. Series from a list

We have already seen this in the previous examples. A list can be passed to the Series function to create a Series.

list_a = ['data', 'science', 'machine', 'learning']ser = pd.Series(list_a)type(ser)
pandas.core.series.Series

5. Series from a NumPy array

Another common way to create a Series is using a NumPy array. It is just like creating from a list. We only change the data passed to the Series function.

arr = np.random.randint(0, 10, size=50)ser = pd.Series(arr)

6. Accessing individual values

Since Series contains labelled items, we can access to a particular item using the label (i.e. the index).

ser = pd.Series(['a','b','c','d','e'])print(ser[0])
a
print(ser[2])
c

7. Slicing a Series

We can also use the index to slice a Series.

ser = pd.Series(['a','b','c','d','e'])print(ser[:3])
0 a
1 b
2 c
dtype: object
print(ser[2:])
2 c
3 d
4 e
dtype: object

8. Data types

Pandas assigns an appropriate data type when creating a Series. We can change it using the dtype parameter. Of course, an appropriate data type needs to be selected.

ser1 = pd.Series([1,2,3,4,5])
print(ser1)
0 1
1 2
2 3
3 4
4 5
dtype: int64
ser2 = pd.Series([1,2,3,4,5], dtype='float')
0 1.0
1 2.0
2 3.0
3 4.0
4 5.0
dtype: float64

9. Number of items in a Series

There are multiple ways to count the number of values in a Series. Since it is a collection, we can use the built-in len function of Python.

ser = pd.Series([1,2,3,4,5])len(ser)
5

We can also use the size and shape functions of Pandas.

ser.size
5
ser.shape
(5,)

The shape function returns the size in each dimension. Since a Series is one-dimensional, we get the length from the shape function. Size returns the total size of a Series or DataFrame. If used on a DataFrame, size returns the product of the number of rows and columns.

10. Unique and Nunique

The unique and nunique functions return the unique values and the number of unique values, respectively.

ser = pd.Series(['a','a','a','b','b','c'])ser.unique()
array(['a', 'b', 'c'], dtype=object)
ser.nunique()
3

11. Largest and smallest values

The nlargest and nsmallest functions return the largest and smallest values in a Series. We get the 5 largest or smallest values by default but it can be changed using the n parameter.

ser = pd.Series(np.random.random(size=500))ser.nlargest(n=3)
292 0.997681
236 0.997140
490 0.996117
dtype: float64
ser.nsmallest(n=2)
157 0.001499
140 0.002313
dtype: float64

12. Series from a dictionary

If we pass a dictionary to the series function, the returned series contains the values of the dictionary. The index is the keys of the dictionary.

dict_a = {'a':1, 'b':2, 'c':8, 'd':5}pd.Series(dict_a)
a 1
b 2
c 8
d 5
dtype: int64

13. Converting data type

We have the option to choose a data type when creating a Series. Pandas allows for changing the data type later on as well.

For instance, the following series contains integers but stored with object dtype. We can use the astype function to convert them to integers.

ser = pd.Series(['1','2','3','4'])ser
0 1
1 2
2 3
3 4
dtype: object
ser.astype('int')
0 1
1 2
2 3
3 4
dtype: int64

14. Number of occurrences of values

The value_counts function returns the number of occurrences of each unique value in a Series. It is useful to get an overview of the distribution of values.

ser = pd.Series(['a','a','a','b','b','c'])ser.value_counts()
a 3
b 2
c 1
dtype: int64

15. From series to list

Just like we can create a Series from a list, it is possible to convert a Series to a list.

ser = pd.Series(np.random.randint(10, size=10))ser.to_list()
[8, 9, 0, 0, 7, 1, 8, 6, 0, 8]

16. Null values

It is likely to have missing values in a Series. Pandas makes it very simple to detect and deal with missing values.

For instance, the count function returns the number of non-missing values in a Series.

ser = pd.Series([1, 2, 3, np.nan, np.nan])ser.count()
3

17. Null values — 2

Another way to detect missing values is the isna function. It returns the Series with boolean values indicating missing values with True.

ser = pd.Series([1, 2, 3, np.nan, np.nan])ser.isna()
0 False
1 False
2 False
3 True
4 True
dtype: bool

We can count the number of missing values by chaining the sum function with the isna function.

ser.isna().sum()
2

18. Rounding up floating point numbers

In data analysis, we are most likely to have numerical values. Pandas is highly capable of manipulating numerical data. For instance, the round function allows for rounding the floating points numbers up to a specific decimal points.

Consider the following Series.

ser
0 0.349425
1 0.552831
2 0.104823
3 0.899308
4 0.825984
dtype: float64

Here is how the round function is used:

ser.round(2)
0 0.35
1 0.55
2 0.10
3 0.90
4 0.83
dtype: float64

19. Logical operators

We can apply logical operators to a Series such as equal, less than, or greater than. They return the Series with boolean values indicating the values that fit the specified condition with True.

ser = pd.Series([1, 2, 3, 4])ser.eq(3)
0 False
1 False
2 True
3 False
dtype: bool
ser.gt(2)
0 False
1 False
2 True
3 True
dtype: bool

The entire list of logical operators:

  • lt : Less than
  • le: Less than or equal
  • gt: Greater than
  • ge: Greater than or equal
  • eq: Equal
  • ne: Not equal

20. Data aggregations

We can apply aggregate functions on a Series such as mean, sum, median an so on. One way to apply them separately on a Series.

ser = pd.Series([1, 2, 3, 4, 10])ser.mean()
4

There is a better way if we need to apply multiple aggregate functions. We can pass them in a list to the agg function.

ser.agg(['mean','median','sum', 'count'])mean       4.0
median 3.0
sum 20.0
count 5.0
dtype: float64

Conclusion

We have done 20 examples that demonstrate the properties of Series and the functions to interact with it. It is just as important as DataFrame because a DataFrame is composed of Series.

The examples in this article cover a great deal of commonly used data operations with Series. There are, of course, more functions and methods to be used with Series. You can learn more advanced or detailed operations as you need them.

Thank you for reading. Please let me know if you have any feedback.

2021년 1월 27일 성남시 분당구 부동산 경매 데이터 분석

2021년 1월 27일 용인시 부동산 경매 데이터 분석

2021년 1월 27일 수원시 부동산 경매 데이터 분석

2021년 1월 26일 모바일 게임 매출 순위

Rank Game Publisher
1 리니지M NCSOFT
2 리니지2M NCSOFT
3 세븐나이츠2 Netmarble
4 기적의 검 4399 KOREA
5 Cookie Run: Kingdom Devsisters Corporation
6 메이플스토리M NEXON Company
7 라이즈 오브 킹덤즈 LilithGames
8 V4 NEXON Company
9 Genshin Impact miHoYo Limited
10 S.O.S:스테이트 오브 서바이벌 KingsGroup Holdings
11 뮤 아크엔젤 Webzen Inc.
12 FIFA ONLINE 4 M by EA SPORTS™ NEXON Company
13 블레이드&소울 레볼루션 Netmarble
14 리니지2 레볼루션 Netmarble
15 PUBG MOBILE KRAFTON, Inc.
16 KartRider Rush+ NEXON Company
17 미르4 Wemade Co., Ltd
18 바람의나라: 연 NEXON Company
19 찐삼국 ICEBIRD GAMES
20 R2M Webzen Inc.
21 Lords Mobile: Kingdom Wars IGG.COM
22 블리치: 만해의 길 DAMO NETWORK LIMITED
23 Empires & Puzzles: Epic Match 3 Small Giant Games
24 Roblox Roblox Corporation
25 Pokémon GO Niantic, Inc.
26 A3: 스틸얼라이브 Netmarble
27 명일방주 Yostar Limited.
28 검은강호2: 이터널 소울 9SplayDeveloper
29 Epic Seven Smilegate Megaport
30 라그나로크 오리진 GRAVITY Co., Ltd.
31 Age of Z Origins Camel Games Limited
32 Gardenscapes Playrix
33 그랑삼국 YOUZU(SINGAPORE)PTE.LTD.
34 AFK 아레나 LilithGames
35 검은사막 모바일 PEARL ABYSS
36 Brawl Stars Supercell
37 Pmang Poker : Casino Royal NEOWIZ corp
38 Top War: Battle Game Topwar Studio
39 FIFA Mobile NEXON Company
40 한게임 포커 NHN BIGFOOT
41 Homescapes Playrix
42 Cookie Run: OvenBreak – Endless Running Platformer Devsisters Corporation
43 붕괴3rd miHoYo Limited
44 랑그릿사 ZlongGames
45 Summoners War Com2uS
46 컴투스프로야구2021 Com2uS
47 Teamfight Tactics: League of Legends Strategy Game Riot Games, Inc
48 사신키우기 온라인 : 경이로운 사신 ep1 DAERISOFT
49 Random Dice: PvP Defense 111%
50 가디언 테일즈 Kakao Games Corp.

Are The New M1 Macbooks Any Good for Deep Learning? Let’s Find Out -번역

새로운 M1 맥북이 딥 러닝에 좋은가요?알아 보자

기본 딥 러닝 작업을위한 M1 Mac 대 Google Colab

Photo by veeterzy from Pexels

새로운 Apple M1 칩 뒤에는 많은 과장이 있습니다.지금까지 인텔이 제공 한 모든 것보다 우수한 것으로 입증되었습니다.그러나 이것이 딥 러닝에 어떤 의미가 있습니까?그것이 오늘 여러분이 알게 될 것입니다.

새로운 M1 칩은 단순한 CPU가 아닙니다.MacBook Pro에서는 8 코어 CPU, 8 코어 GPU 및 16 코어 신경 엔진으로 구성됩니다.프로세서와 GPU는 모두 이전 세대 Intel 구성보다 훨씬 우수합니다.

저는 이미 M1 칩이 얼마나 빠른지 시연했습니다.정규 데이터 과학 작업,하지만 딥 러닝은 어떻습니까?

에스hort 대답 — 예,이 부서에는 약간의 개선이 있습니다.하지만 이제는 Mac이Google Colab?Colab은 완전히 무료 옵션입니다.

기사는 다음과 같이 구성됩니다.

  • CPU 및 GPU 벤치 마크
  • 성능 테스트 — MNIST
  • 성능 테스트 — Fashion MNIST
  • 성능 테스트 — CIFAR-10
  • 결론

중요 사항

모든 데이터 과학 라이브러리가 아직 새로운 M1 칩과 호환되는 것은 아닙니다.TensorFlow (버전 2.4)가 제대로 작동하도록하는 것은 말처럼 쉽지 않습니다.

당신은 참조 할 수 있습니다이 링크.whlTensorFlow 용 파일 및 종속성입니다.이것은 macOS 11.0 이상에만 해당하므로 명심하십시오.

여러분이 보게 될 테스트는 어떤 식 으로든, 형태 나 형태가“과학적”이 아닙니다.에포크 당 평균 훈련 시간 만 비교합니다.

CPU 및 GPU 벤치 마크

먼저 기본 CPU 및 GPU 벤치 마크부터 시작하겠습니다.M1 칩이 장착 된 새로운 MacBook Pro와 2019 년의 기본 모델 (Intel)을 비교합니다.Geekbench 5테스트에 사용되었으며 아래 결과를 볼 수 있습니다.

이미지 1 — Geekbench 5 결과 (Intel MBP 대 M1 MBP) (작성자 별 이미지)

결과는 스스로를 말해줍니다.M1 칩은 2019 년 Mac에서 Intel 칩을 철거했습니다.지금까지는 유망 해 보입니다.

성능 테스트 — MNIST

MNIST 데이터 세트는 딥 러닝의 “hello world”와 같습니다.TensorFlow에 내장되어있어 훨씬 쉽게 테스트 할 수 있습니다.

다음 스크립트는 MNIST 데이터 세트에서 10 개의 Epoch에 대해 신경망 분류기를 훈련합니다.M1 Mac을 사용하는 경우mlcompute라인, 이것들은 일이 조금 더 빠르게 실행되도록 만듭니다.

위의 스크립트는 M1 MBP 및 Google Colab (CPU 및 GPU 모두)에서 실행되었습니다.아래에서 런타임 비교를 볼 수 있습니다.

이미지 2 — MNIST 모델 평균 학습 시간 (작성자 별 이미지)

결과는 새로운 Mac에 대해 다소 실망 스럽습니다.Colab은 CPU 및 GPU 런타임 모두에서이를 능가했습니다.Colab의 런타임 환경이 보장되지 않으므로 결과는 다를 수 있습니다.

성능 테스트 — Fashion MNIST

이 데이터 세트는 일반 MNIST와 매우 유사하지만 손으로 쓴 숫자 대신 옷 조각이 포함되어 있습니다.따라서 훈련에 동일한 신경망 아키텍처를 사용할 수 있습니다.

보시다시피 여기서 변경된 유일한 것은 데이터 세트를로드하는 데 사용되는 함수입니다.동일한 환경에 대한 런타임 결과는 다음과 같습니다.

이미지 3 — Fashion MNIST 모델 평균 교육 시간 (작성자 별 이미지)

다시 한 번 비슷한 결과를 얻었습니다.이 데이터 세트는 MNIST와 매우 유사하므로 예상됩니다.

하지만 더 복잡한 데이터 세트와 신경망 아키텍처를 도입하면 어떻게 될까요?

성능 테스트 — CIFAR-10

CIFAR-10은 또한 “hello world”딥 러닝 데이터 세트의 범주에 속합니다.여기에는 비행기, 새, 고양이, 개, 배, 트럭 등 10 가지 범주의 60K 이미지가 포함되어 있습니다.

이미지의 크기는 32x32x3이므로 사람도 분류하기 어려운 경우도 있습니다.아래 스크립트는 세 개의 컨벌루션 레이어를 사용하여 분류기 모델을 학습시킵니다.

컨볼 루션 레이어와 더 복잡한 아키텍처가 런타임에 어떤 영향을 미치는지 살펴 보겠습니다.

이미지 4 — CIFAR-10 모델 평균 교육 시간 (작성자 별 이미지)

보시다시피 Colab의 CPU 환경은 GPU 및 M1 환경에 가깝지 않습니다.Colab GPU 환경은 이전 두 테스트와 유사하게 Apple의 M1보다 약 2 배 더 빠릅니다.

결론

저는 새로운 M1 칩의 모든 부분과 함께 제공되는 모든 것을 좋아합니다. 더 나은 성능, 과열 없음, 더 나은 배터리 수명.그래도 딥 러닝에 관심이 있다면 추천하기 어려운 노트북입니다.

물론, 다른 Intel 기반 Mac보다 M1이 약 2 배 향상되었지만 여전히 딥 러닝을 위해 만들어진 기계는 아닙니다.오해하지 마세요. 기본적인 딥 러닝 작업에 MBP를 사용할 수 있지만 매일 딥 러닝을 수행한다면 동일한 가격대에 더 나은 머신이 있습니다.

이 기사에서는 단순한 데이터 세트에 대한 딥 러닝 만 다루었습니다.다음은 M1 칩과 Colab을 비교하여 전이 학습과 같은 더 까다로운 작업을 수행합니다.

읽어 주셔서 감사합니다.

LinkedIn에서 연결하세요.

원래 게시 된 위치https://www.betterdatascience.com2021 년 1 월 25 일.

Are The New M1 Macbooks Any Good for Deep Learning? Let’s Find Out

Are The New M1 Macbooks Any Good for Deep Learning? Let’s Find Out

M1 Macs vs. Google Colab for basic deep learning tasks

Photo by veeterzy from Pexels

There’s a lot of hype behind the new Apple M1 chip. So far, it’s proven to be superior to anything Intel has offered. But what does this mean for deep learning? That’s what you’ll find out today.

The new M1 chip isn’t just a CPU. On the MacBook Pro, it consists of 8 core CPU, 8 core GPU, and 16 core neural engine, among other things. Both the processor and the GPU are far superior to the previous-generation Intel configurations.

I’ve already demonstrated how fast the M1 chip is for regular data science tasks, but what about deep learning?

Short answer — yes, there are some improvements in this department, but are Macs now better than, let’s say, Google Colab? Keep in mind, Colab is an entirely free option.

The article is structured as follows:

  • CPU and GPU benchmark
  • Performance test — MNIST
  • Performance test — Fashion MNIST
  • Performance test — CIFAR-10
  • Conclusion

Important notes

Not all data science libraries are compatible with the new M1 chip yet. Getting TensorFlow (version 2.4) to work properly is easier said than done.

You can refer to this link to download the .whl files for TensorFlow and it’s dependencies. This is only for macOS 11.0 and above, so keep that in mind.

The test you’ll see aren’t “scientific” in any way, shape or form. They only compare the average training time per epoch.

CPU and GPU benchmark

Let’s start with the basic CPU and GPU benchmarks first. The comparison is made between the new MacBook Pro with the M1 chip and the base model (Intel) from 2019. Geekbench 5 was used for the tests, and you can see the results below:

Image 1 — Geekbench 5 results (Intel MBP vs. M1 MBP) (image by author)

The results speak for themselves. M1 chip demolished Intel chip in my 2019 Mac. So far, things look promising.

Performance test — MNIST

The MNIST dataset is something like a “hello world” of deep learning. It comes built-in with TensorFlow, making it that much easier to test.

The following script trains a neural network classifier for ten epochs on the MNIST dataset. If you’re on an M1 Mac, uncomment the mlcompute lines, as these will make things run a bit faster:

The above script was executed on an M1 MBP and Google Colab (both CPU and GPU). You can see the runtime comparisons below:

Image 2 — MNIST model average training times (image by author)

The results are somewhat disappointing for a new Mac. Colab outperformed it in both CPU and GPU runtimes. Keep in mind that results may vary, as there’s no guarantee of the runtime environment in Colab.

Performance test — Fashion MNIST

This dataset is quite similar to the regular MNIST, but is contains pieces of clothing instead of handwritten digits. Because of that, you can use the identical neural network architecture for the training:

As you can see, the only thing that’s changed here is the function used to load the dataset. The runtime results for the same environments are shown below:

Image 3 — Fashion MNIST model average training times (image by author)

Once again, we get similar results. It’s expected, as this dataset is quite similar to MNIST.

But what will happen if we introduce a more complex dataset and neural network architecture?

Performance test — CIFAR-10

CIFAR-10 also falls into the category of “hello world” deep learning datasets. It contains 60K images from ten different categories, such as airplanes, birds, cats, dogs, ships, trucks, etc.

The images are of size 32x32x3, which makes them difficult to classify even for humans in some cases. The script below trains a classifier model by using three convolutional layers:

Let’s see how convolutional layers and more complex architecture affects the runtime:

Image 4 — CIFAR-10 model average training times (image by author)

As you can see, the CPU environment in Colab comes nowhere close to the GPU and M1 environments. The Colab GPU environment is still around 2x faster than Apple’s M1, similar to the previous two tests.

Conclusion

I love every bit of the new M1 chip and everything that comes with it — better performance, no overheating, and better battery life. Still, it’s a difficult laptop to recommend if you’re into deep learning.

Sure, there’s around 2x improvement in M1 than my other Intel-based Mac, but these still aren’t machines made for deep learning. Don’t get me wrong, you can use the MBP for any basic deep learning tasks, but there are better machines in the same price range if you’ll do deep learning daily.

This article covered deep learning only on simple datasets. The next one will compare the M1 chip with Colab on more demanding tasks — such as transfer learning.

Thanks for reading.

Connect on LinkedIn.

Originally published at https://www.betterdatascience.com on January 25, 2021.

2021년 1월 26일 성남시 분당구 부동산 경매 데이터 분석

2021년 1월 26일 용인시 부동산 경매 데이터 분석