반응형

아래 내용은 Udemy에서 Pytorch: Deep Learning and Artificial Intelligence를 보고 정리한 내용이다.

7. what is machine learning?

machine learning 이란?

복잡

machine learning is nothing but a geometry problem

 

regression number

fit a line or curve

예측 

y hat = mx + b

make the line/curve close to the data points

 

classification category/label

target 

separate 

make the line/curve separate data points of different classes

 

supervised learning 

 

8. regression basics

tensorflow 

dataset

x-axis

y-axis

 

scikit-learn approach

load the data  => pd.read_csv()

 

1. model architecture model = LinearRegression()

2. model.predict(X)

3. model.fit(X, y)

 

loss function

loss = cost == error = objective

 

pytorch 다른점

no predefined models

no fit or predict

 

mse loss 함수 

Mean Squared Error : 차이  

error가 작으면 작을 수록 good fit이고 

크면 bad fit

perfect fit = zero error

 

linear regression

 

gradient descent

 

9. Regression Code Preparation

Regression code preparation

 

cocepts는 같지만 코드는 다르다.

python loop

for i in range(10):

  print(i)

 

java loop

for(int i = 0; i < 10; i++){

  System.out.println(i);

}

we konw the concepts, but not the syntax

 

#1. build the model

model = nn.Linear(1,1)

 

#2. train the model

#loss and optimizer

criterion = nn.MSELoss()

optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

 

 

#Train the model(gradient descent loop)

n_epochs = 30

for it in range(n_epochs):

 # zero the parameter gradients

  optimizer.zero_grad()

  # gradient 

  # forward pass

  outputs= model(inputs)

  loss = criterion(outputs, targets)

  # backward and optimize

  loss.backward()

  optimizer.step()

 

(inputs, targets)

(X, y)

pytorch에서 numpy 는 안된다. tensor은 된다.

Array to tensor

X = X.reshape(N,1)

Y = Y.reshape(N,1)

 

#pytorch는 type에 엄청 까다롭다.

#pytorch는 float32 default

#numpy float64 default

inputs = torch.from_numpy(X.astype(np.float32))

targets = torch.from_numpy(Y.astype(np.float32)

 

#3. make predictions

#Forward pass

outpus = model(inputs)

<- No, this just gives us a Torch Tensor

pytorch는 tensor 가능하다. 

 

predictions = model(inputs).detach().numpy()

<-Detach from graph(more detail later), and convert to Numpy array

 

 

summary:

 

10. Regression Notebook

import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
N = 20
X= np.random.random(N) * 10 -5
y = 0.5 * X - 1 +np.random.randn(N)
plt.scatter(X,y )

linear one input one output

model = nn.Linear(1,1)
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
X = X.reshape(N, 1)
y = y.reshape(N, 1)

inputs = torch.from_numpy(X.astype(np.float32))
targets = torch.from_numpy(y.astype(np.float32))
type(inputs)

torch.Tensor =>torch.Tensor

n_epochs = 30
losses = []
for it in range(n_epochs):

  optimizer.zero_grad()

  outputs= model(inputs)
  loss = criterion(outputs, targets)

  losses.append(loss.item())

  loss.backward()
  optimizer.step()

  print(f'Epoch {it+1}/{n_epochs}, Loss:{loss.item():.4f}')

 

plt.plot(losses)

prediction 

predicted = model(inputs).detach().numpy()
plt.scatter(X, y , label ='Original data')
plt.plot(X, predicted, label ='Fitted lne')
plt.legend()
plt.show()

#Error
model(inputs).numpy()

with torch.no_grad():
  output = model(inputs).numpy()
output

w = model.weight.data.numpy()
b = model.bias.data.numpy()
print(w, b)

 

 

 

11. 무어의 법칙

무어의 법칙은 컴퓨터구조에서 배운다. 

컴퓨터 power 은 grows exponentially.

2배씩 

 

computer power

 exponentailly eg, 1,2,4,8,...

 

y = ax+ b=> linear 함수 

 

normalize

 

 

12. Moore's Law Notebook

데이터를 

 

Error tokenizing data  오류가 날 경우에는

error_bad_lines=False 추가한다.

 

 

 데이터가 바꿔져서 그런지 오류가 나서 진행이 안된다.

 

데이터 가공

모델 생성

loss 

모델 학습

모델 predict

 

 

transforming back to original scale

import torch
import torch.nn as nn
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('moore.csv' , header= None , error_bad_lines=False).values
data

 

 

13. Linear Classification Basics

regression: we want the line to be close to the data points

classification : we want the line to separate data points

  tensorflow 모델 학습  pytorch
1. load in some data    
2. model 생성 model = MyLinearClassifier()  
3. train model model.fit(X,y) 없다.
4. predictions model.predict(X_test) 없다.
5. evaluate accuracy model.score(X,y)  

accuracy = #correct / #total

error = #incorrect/ #total

error = 1- accuracy

 

linear

a = w1x1+w2x2 +b

if a>= 0 -> predict 1

if a<   0 -> predict 0

sigmoid 0 ~ 1 사이의 값

 

model architecture

making predictions

training

 

14. Classification Code Prepatration

loading in the data

from sklearn.datasets import load_breast_cancer

data = load_breast_cancer()
X,y = data.data, data.target

preprocess the data

split the data

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =0.3)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

build the model

Recall: the shape of the data is "NxD"

model = nn.Sequentail(

  nn.Linear(D,1),

  nn.Sigmoid()

)

input each feature for dataset

 

Train the model

#loss and optimizer

criterion = nn.BCELoss() #binary cross entropy 

optimizer = torch.optim.Adam(model.parameters()) #adam hypperparammeter

 

for it in range(n_epochs):

  optimizer.zero_grad()

 

hypperparameter

 

evaluating the model

Recall : in regression , we use the MSE(loss)

RMSE 도 가능하다.

 

GET THE ACCURACY:

with torch.no_grad():

  p_train = model(X_train)

  p_train = np.round(p_train.numpy())

  train_acc = np.mean(y_train.numpy() == p_train)

 

 

15. Classification Notebook

pytorch Classification code

import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer

data = load_breast_cancer()
type(data)

data.keys()

shape를 확인한다.

data.data.shape

 

569 데이타 가 있고 30개 feature이 있다.

data.target

data.target_names

data.target.shape

data.feature_names

data split

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size =0.3)
N, D = X_train.shape

normalization or standardscaler

from sklearn.preprocessing import StandardScaler


scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

 

pytorch build model

model = nn.Sequential(
  nn.Linear(D,1),
  nn.Sigmoid()
)

 

loss and optimizer

criterion = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters())

 

convert data tensor

2d array -> 1d array

X_train = torch.from_numpy(X_train.astype(np.float32))
X_test = torch.from_numpy(X_test.astype(np.float32))
y_train = torch.from_numpy(y_train.astype(np.float32).reshape(-1,1))
y_test = torch.from_numpy(y_test.astype(np.float32).reshape(-1,1))
epochs = 1000
train_losses = np.zeros(epochs)
test_losses = np.zeros(epochs)

for epoch in range(epochs):
  optimizer.zero_grad()

  outputs = model(X_train)
  loss = criterion(outputs, y_train )

  outputs_test = model(X_test)
  loss_test = criterion(outputs_test, y_test)

  #save losses
  train_losses[epoch] = loss.item()
  test_losses[epoch] = loss_test.item()

  if (epoch+1) % 50 == 0: 
    print(f'Epoch {epoch+1}/ {epochs} , Train loss: {loss.item():.4f} , Test loss: {loss_test.item():.4f}'  )

 

plt.plot(train_losses , label = 'train loss')
plt.plot(test_losses , label = 'test loss')
plt.legend()
plt.show()

#loss function 

accuracy 

# get Accuracy
with torch.no_grad():
  p_train = model(X_train)
  p_train = np.round(p_train.numpy())
  train_acc = np.mean(y_train.numpy() == p_train)

  p_test = model(X_test)
  p_test = np.round(p_test.numpy())
  test_acc = np.mean(y_test.numpy() == p_test)

print(f"Train acc: {train_acc:.4f} , Test acc:{test_acc:.4f}")

 

loss and accuracy 

plt.plot(train_acc , label = 'train acc')
plt.plot(test_acc , label = 'test acc')
plt.legend()
plt.show()

 

16. Saving and loading a model

pytorch saving and loading model

dictionary 

model.state_dict()

 

save the model

torch.save(model.state_dict(), 'myFirstModel.pt')
!ls

model1 = nn.Sequential(
  nn.Linear(D,1),
  nn.Sigmoid()
)
model1.load_state_dict(torch.load('myFirstModel.pt'))

# get Accuracy
with torch.no_grad():
  p_train = model1(X_train)
  p_train = np.round(p_train.numpy())
  train_acc = np.mean(y_train.numpy() == p_train)

  p_test = model1(X_test)
  p_test = np.round(p_test.numpy())
  test_acc = np.mean(y_test.numpy() == p_test)

print(f"Train acc: {train_acc:.4f} , Test acc:{test_acc:.4f}")

google colab 모델 다운로드 하기

from google.colab import files
files.download('myFirstModel.pt')

구글에서 다운로드가 된다.

 

17. A short Neuroscience Primer

linear regression   y = ax + b

logistic regression

 

nueron network 

nueron

senses -> signals 

 

18. How does a model "learn"?

linear regression

line of best fit

 

mse mean squared error

minimizing cost -> making small is possible 

gradient ->기울기 

 

gradient Descent 

gradient zero 

epochs to train

 

gradient Descent 

learning rate -> hyperparameter

 

 

19. Model With logits

전 부 같은데 모델 생성하는 부분이 다르다.

계산이 포함 되여 있어서 sigmoid 필요없다.

 

model2 = nn.Linear(D,1)

criterion = nn.BCELoss()
optimizer = torch.optim.Adam(model2.parameters())

 

prediction 도 다르다.

숫자로 결과를 나오기 때문에 확인 해야 한다.

# get Accuracy
with torch.no_grad():
  p_train = model2(X_train)
  p_train = np.round(p_train.numpy() > 0)
  train_acc = np.mean(y_train.numpy() == p_train)

  p_test = model2(X_test)
  p_test = np.round(p_test.numpy() > 0)
  test_acc = np.mean(y_test.numpy() == p_test)

print(f"Train acc: {train_acc:.4f} , Test acc:{test_acc:.4f}")

 

20 Train Sets vs. Validation Sets vs. Test Sets

overfitting을 방지하기 위하여 데이터 셋을 나눈다.

optimim 찾기

 

cross-validation

hypperparameter 

 

 

21. Suggestion Box

 

 

반응형
반응형

아래 내용은 Udemy에서 Pytorch: Deep Learning and Artificial Intelligence를 보고 정리한 내용이다.

 

01. Introduction

1. Welcome

pytorch : simple and easy

CNNs

RNNs - sequence data

Stock Prediction with RNNs

GANs

Deep Reinforcement Learnin g: 강화학습 

  알파고

NLP

Object detection

facial recognition

deep fakes

 

2. overview and outline

tensorflow 업그레이드 되여서 간단해졌지만  high level

보통적인 것은 쉽지만 , 특수화 된것은 어렵다.

pytorch는 no need to use linear algebra and calculus to derive backpropagation

  gpu 

google colab

Jupyter Notebook but hosted by Google

 

NLP 

Text classification

Embeddings

 

 

Transfer Learning

Their Network + Your Network

combine Your Network with theirs - get a state-of-the-art deep net within seconds

 

3. where to get the code

google colab

git clone <url>

git pull  -> 마지막 버전 

경험이다.

Theory lecture -> code lecture -> Possible extensions

 

02. Google Colab

4. jupyter notebook, goolge colab

download datafiles

access to GPU and TPU(Tensor Processing Unit)

stored in Google Driver( the "cloud")

many libiriary

 

google drive  

Google colab이 안보일 경우 

Connect More apps ->More menu -> colab

없을 경우 connect more apps

 

gpu, tpu 설정 runtimes에 가서 설정해야 한다.

runtime 연형변경

 

아래에 따라 code, text 추가하기 

 

위의 조절함에 따라 글자체가 달라진다.

제목을 할것인지 선택하면 된다.

 

코드 추가하기 

numpy, plt추가하기 

import numpy as np
import matplotlib.pyplot as plt

예제

x = np.linspace(0, 10* np.pi, 1000)
y = np.sin(x)
plt.plot(x,y)

note book 이여서 plt.show()를 할 필요 없다.

 

 

__version__으로 버전 확인 하기

import tensorflow as tf
tf.__version__

disconnected일경우에는 다시 연결하면 된다. Reconnect

오래 동안 하지 않을 경우 에 메시지가 띄운다.

run out of memory 할 수 도 있다.

 

5. Uploading your own data to google colab

down load th data from a url

!wget를 사용한다.

데이터 다운로드 하기

!wget를 사용하여 데이터 다운로드 하기

 

!ls  =>  로 해당 경로 list확인 하기

!head  => 앞의 몇 라인을 확인하기 , head row 있는지도 확인하기

 

헤더가 없어서 header = None으로 확인 한다.

import pandas as pd
df = pd.read_csv('arrhythmia.data', header = None)

여러가지 컬럼이 있기 때문에 앞의 몇개를 가공하면서 사용한다.

data = df[[0,1,2,3,4,5]]
data.columns = ['age', 'sex', 'height', 'weight', 'QRS duration' , 'P-R interval']

document를 활용하여 데이터의 정보를 알 수 있다.

!head arrhythmia.data

 

마지막에 ;을 하는게 좋다. 

import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [15,15]
data.hist();

 

 

from pandas.plotting import scatter_matrix
scatter_matrix(data);

 

part 2: USING tf.keras

tensorflow 를 사용하는 이유는 pytorch만 사용할 수 없기 때문에 tensorflow 도 같이 사용할 떄도 있다.

 

tensorflow downgrade

!pip install -q tensorflow==2.0.0-beta1
import tensorflow as tf
print(tf.__version__)

 

다운했는데도 불구하고 버전이 바꿔지지 않을 경우에는 runtime을 다시 시작하면 된다.

다시 수행할 경우에는 

 

tf.keras.utils.get_file('auto-mpg.data', url)

!head '/root/.keras/datasets/auto-mpg.data'

 

헤더와 whitespace를 확인한다.

import pandas as pd
df = pd.read_csv('/root/.keras/datasets/auto-mpg.data', header = None, delim_whitespace=True)
df.head()

 

upload the file youself

from google.colab import files
uploaded = files.upload()

 

파일을 선택하여 할 수 있다.

dictionary를 확인할 수 있다.

uploaded

!ls

 

import pandas as pd
df = pd.read_csv('daily-minimum-temperatures-in-me.csv', error_bad_lines=False)
df.head()
from google.colab import files
uploaded = files.upload()

 

함수의 이름을 보여준다.

from fake_util import my_useful_function
my_useful_function()

!pwd

access file from google drive

mount the dirve

from google.colab import drive
drive.mount('/content/gdrive')

url 클릭후 코드 복사해서 넣는다.

 

!ls
!ls gdrive

google drive에 뭐 있는지 확인한다.

!ls '/content/gdrive/My Drive'

 

6. where can I learn about numpy, scipy, matplotlib, pandas, and Scikit-learn?

Numpy

matrix arighmetic

tensors(arrays) Tensorflow로 왔다.

1-D tensor (vector)

2-D tensor (matrix)

3-D and 4-D tensors

계산 

matrix multiply = dot/inner procuct(np.dot

element-wise multiply(x)

 

matplot

그림 

 

pandas

loading data

 

scipy

no real use of this (so far)

numpy is lowe-level: adding, multiplying

power version of Numpy

 

scikit-learn

basic machine learning

 

Machine Learning step

1. Load in the data

2. split into trian/test sets

3. build a model

4. fit the model(gradient descent)

5. evaluate the model  -> accuracy

   overfitting and underfitting

6. make predictions <- need to convert between Numpy array and Torch Tensor

 

반응형
반응형

 

본 내용은  fastcampus 딥러닝/인공지능 올인원 패키지 online을 정리한 것이다.

 

파이썬 개발 환경 설정

anaconda 설치  

  python 3.7 

jupyter notebook 

 

anaconda

jupyter 환경에서 하게 된다.

 

파이썬 개발 환경 설정

anaconda 통합 platform이다. 

각 플렛폼 마다 다르다.

다운된 것을 실행 하면 된다. 

install 기본값으로 

anaconda 환경을 기본환경으로 한다는 것만 check하면 된다.

 

Jupyter notebook 설치 및 사용법 소개

New를 하면 언어를 선택 가능 python3로 하면 된다.

 

마우스 클릭하고 esc눌리면

cell 은 실행할 코드나 주석 등을 입력

 

녹색    : 타이핑 가능 입력 모드

파란색 : 명령어를 할수 있다. 명령 모드

 

명령 모드 파란색 

명령어 모드에서 h를 눌리면 키보드 단축키가 나온다. -> help

 

cell추가하면 위에 a

cell 아래 추가하면 b

d 두번 눌리면 지우기

 

shift+ enter : cell 실행하고 아래로 옮긴다.

ctrl+enter: cell 그냥 실행하고 cursor안옮긴다.

alt + enter: cell 실행하고 아래로 추가한다.

 

jupyter notebook cell의 type: 

in 이것은 type은 코드이다.

cell 가지고 cell type에서 markdown으로 바꿀 수 있다.

 

markdown in이 없어졌다.

코드 입력할려면 in이 있어야 한다.

 

markdown은 문서를 만들때 문서와 구조를 한꺼번에 하는것

코드에 대한것 깔끔하게 하고 싶다.

# 큰 title

##

###

####

코드모드에서 m markdown

markdown에서 코드 모드 y

 

**python** bold

*cool* itelity

 

list로 하고 싶을 떄 - 순서가 없는 

- pyton 

 - pandas

- java

 

순서 

1. python

2. java

 

 > 비교 연산자 들여쓰기 하는 

> 파이썬은 재밌다고 하더라.

 

마크 다운 수학식 지원 

$y = 3x$

 

코드 지원

 

 

'''pytonn

'''

 

한글로 link사용

[파이썬](url)

 

타입 및 변수

데이터 타입과 컬렉션

변수 : 데이터를 저장하는 공간, 변수

저장공간에 값을 생성하고 이름을 지정

=(대입연산자)를 사용하여 왼쪽은 변수명, 오르쪽은 데이터가 위치 변수 혹은 값 

 

= 대입연산자

== 비교연산자

 

정수형과 실수형

a = 1
b = 2.1

 

print함수 

값을 확인 하는 함수 

함수는 특정 기능 먼저 구형하여 그 함수를 반복적으로 호출하여 사용가능한 코드 블록 

이름 명명 규칙에서 숫자로 시작하면 안된다.

해당 변수의 값을 출력

, 로 여러 변수를 나열하면 한줄에 출력

기본적으로는 한칸 띄어쓰기 후 출력

#뒤에 오는 거은 주석이다.

각 print사이에는 enter이다.

a = 10

b = 11.4

print(a, b)
print(a, 10, 200, b)

sep: 구분자 , 각 출력할 변수 사이에서 구별하는 역할을 함

end: 마지막에 출력할 문자열

shift+tab을 이용해서 자세한 정보 볼 수 있다.

print(a, b, 10, 100, sep = "*" , end ="!!")

space를 *로 대체 

원하시는 출력으로 출력 가능하다.

변수 값 확인법 

print()함수 사용

변수 값을 코드의 마지막에 위치 시킨 후 실행 

print(a)
print(a, b)
a

print는 출력만 하지 output이 아니다.

마지막 값이 전체 값의 out으로 나온다.

 

변수이름 규칙

대소문자 

숫자는 사용가능하되 숫자로부터 시작하면 안된다.

 

숫자로 시작하면 안되는 이유?

4 = 9
print(4)

이해하기 쉬운 것으로  명시적으로 이름을 하는게 좋다.

 

또 한가지 안되는 것이 있다.

class 사용할 경우 녹색으로 변해서 예약어있다.

for

while

if

elif

else

class

try

excpt

class

#,,,

이런것을 사용하고 싶을 경우에는 

_class = 100

print(_class)

_ 로 사용해야 한다.

 

05. 데이터 

기본 데이터 타입 4가지 int, float, str, boolean

int: a = 10

flot: b = 11.45

type(A)

 

None : 아무런 값을 갖지 않을 때 사용

c => 이렇게는 안된다.

python은 무조건 초기화해야 한다.

변수 생성하고 싶은 데 어떤 값으로 해야 할지 모를떄 

초기화 값을 모를때 

 

정수와 실수

a = 5
b = 4

# 숫자형이면 비교 가능
#결과는 boolean이다.
print( a > b ) #True
print( a < b) #Flase
print( a >= b) #True
print( a <= b) #False
print( a == b) #False
print( a != b) #True

 

c = a>b
c = True
print(type(c))
print(c)

 

 

여러가지 연산을 다 할 수있다.

변수의 값은 대입하기 전에 값은 변하지 않는다.

a = 5
b = 4

print(a+b)
print(a*b)
print(a-b)
print(a/b)
print(a%b)
print(a**b)

 

a= 5
b = 4

a + b*4

a+b 를 먼저 하고 싶을 경우에는 (a+b) * 4

 

 

연습문제

a = 9
print(a)
print(a-3)
print(a)

 

변수의 값은 대입이 발생하기 전에는 절대 변하지 않는다.

a = 9
a-3
print(a)

 

a= 9
t = a-3
a = t
print(a)

위에것 비효율 적이여서 아래처럼 바꾼다.

a= 9
a = a-3
print(a)

더 줄이기 

a = 9
a-=3
print(a)

- 뿐만 아니라 +, * , / 등 사용가능하다.

 

 

문자열 타입의 이해 및 활용하기

문자열 

생성 4가지 방법

a = ' '

b = " "

위 두개는 차이점이 없다. 문자열 안에서 사용한 것과 다르게 사용하면 된다.  enter 사용 불가 

 

a = ''' '''

b = """ """

위 두개는 enter사용가능하다.

 

차이점이 있다. 출력은 같지만 

 

escape 문자 

문자열 자체로 쓰이는 것이 아니라 특수 효과로 쓰인다.

\n new line

\t tab 등 

 

indexing은 0부터 ㅣ작한다.

마지막 순서는 -1혹은 len()-1

대괄호 이용해서 index사용할 수 있다.

 

python은 음수 index 지원한다.

0부터 시작하고 음수 index도 지원한다.

음수는 뒤에서 부터 시작한다.

 

인덱스의 범위

범위를 초과하면 string index out of range라는 에러가 난다.

유용한 index사용하기 

 

 

문자열 slicing : 부분적으로 짜르는 것 이다.

시작 : 끝  사이의 문자를 가져온다. 

a = 'Hello world'
a[0:4]

0<= <4

생략도 가능하다.

:끝  0 ~ 끝-1

시작:  시작 ~ 끝

: => 시작 부터 끝 

부분 문자열을 추출 할때

 

문자열 함수

a = 'hello world'

a. 하고 tab을 눌리면 

upper()  대문자

replace('','')

 

format 

temperature = 25.5
prob = 80.0
a = '오늘 기온{}도 이고 , 비율 확률은 {}% 입니다.'.format(temperature, prob)
print(a)

split

.split() 띄여쓰기를 기준으로 한다.

.split('w') 문자열 혹은 기타로 하고 싶을 때  w 기준으로 하고 싶을 때  

a = 'hello world what a nice weather'
a.split('w')

 

 

컬렉션 타입 이해  (List)

컬렉션 -> 어떤 것들의 모음이다. 모음이 어떤 목적에 의해서 모은것인지

list & tuple

list순서가 있는  추가 , 삭제 등 가능 동적으로 크기가 변경 가능

tuple 생성된 후에 변경 불가능

 

list

a = [] 

a = [1,2,3,4,5]

a = 'hello world'

b = list(a)

 

split() 함수 

indexing 

문자열 

a = 'hello wold'

print(a[0]

a[0] = 'j' => 어레가 난다. 'str' objects does not support item assignment

문자열은 불변(immutable) 변경이 안된다. 그래서 다시 생성하거나

문자열이 생성되면 절대 바꿀 수 없다. 

b = 'jello world'

c = 'j'+a[1:]

혹은 replace()함수를 사용해서 

a.replace('h','j') 하지만 a자체는 변하지 않는다 . 출력만 한다.  값을 바꾸려면 대입을 해야 한다.

 

list는 바꿀 수 있다.

a =[1,2,3,4]

a[0] = 100

 

리스트 slicing 

 start: end : increment(1)

 

값 추가 및 바꾸는것

 

컬렉션 타입 이해 -2 (List)

list에도 멤버 함수가 있다.

list에 값을 추가하는것 

.append() 리스트의 끝에 항목을 추가

.extend() 리스트를 연장 += 로도 가능함

a = [1,2,3,4,5]

b = [6,7,8,9,10]

#[1,2,3,4,5,6,7,8,9,10]

a.append(b)

[1,2,3,4,5,[6,7,8,9,10]]

a[5]

[6,7,8,9,10]

=>

a.extend(b) 혹은 a+=b

print(a)

 

append는 항상 마지막에 추가

insert() 원하는 위치에 추가

 

remove() 값 지우기 값으로 지운다. 

a.remove(2) 값으로 지우기

지우고 싶은 값이 없을 경우에는 오류가 난다.

pop() 지우고자 하는 아이템을 반환후 , 삭제

 

index() 찾고자 하는 값의 인덱스 반환

값으로 찾기 없을 경우에는 에러 

 

in 키워드 : 리스트 내에 해당 값이 존재하는지 확인

a = [1,2,3,4,5,10]

b = 10

c = b in a # True => b가는 값이 a에 있는 가 ?

 

 

list 정렬

sort() -> 리스트 자체를 내부적으로 정렬

sorted() -> 리스트의 정렬된 복사본을 반환

a= [9,10,7]

a.sort(reverse=True) =>내림차순

 

컬렉션 타입 이해 -3(tuple)

튜플은 괄호를 이용한다. 

a=[1,2,3] =>list

a = (1,2,3) => tuple

tuple은 생성된 후 수정 불가 

 

거의 사용하지 않지만 

사용 원인 

튜플의 값을 차례대로 변수에 대입

a = (100,200)

a = 100, 200 => 괄호를 생략 가능하다. 

type(a)

a, b = (100,200) => multiple return 

print(a,b)

변수 여러개 대입하거나 할 수있어서 편한다. tuple unpacking

함수는 값을 한개 할 수있지만 tuple로 반환하면 여러개 할 수있다.

 

연습문제

a = 5
b = 4

#logic
a = b
b = a

print(a,b)

 

a = 5
b = 4

#logic
temp = a
a = b
b = temp

print(a,b)

a = 5
b = 4

a,b = b,a
print(a,b)

 

컬렉션 타입 이해 -3(dict)

dict : 키와 값을 갖는 데이터 구조

dictionary는 순서가 없고  index가 없다.

a = {}

key , value를 복수개를 가지고 있다.

 

기존에 키가 존재하면 , 새로운 값으로 업데이트

존재하지 않으면 , 추가

동일한 키가 중복으로 두개 있을 수 없다.

value는 여러개 있을 수 있다.

 

update()  두 딕셔너리를 병합함

겹치는 키가 있다면 parameter로 전달되는 키 값이 overwrite된다.

 

key 삭제 

del 키워드 사용 범용적으로 사용할 수 있다. 

pop 함수 이용

a.pop('b') 

del a['b']

 

c = 100

del c

print(c) => undefined

 

딕셔너리의 모든 값을 초기화

clear()

변수명.clear()

 

in  

key값 존재 확인

O(1) 연산 

 

'b' in a

in keyword는 기능이 매우 중요하다.

in list, dict 두개 다 가능하다.

 

a.get('d') ->값이 없어도 오류가 안난다.

a['d']

 

if 'd' in a:

  print(a['d'])

 

keys()  키만 반환

values() 값만 반환

items() 키, 값의 튜플을 반환

list(a.items())

 

 

컬렉션 타입 이해 -3(set)

set은 거의 사용할 일이 없다.

중복이 안되고 순서가 없는 

indexing이 없다. 순서가 없다. 오류가 없다. indexing이 없는 것은 순서가 없다는 것이다. 

a = set()

a={}=>이런식으로 할 수 없다.

b = set(a)

print(b) =>중복이 허용 되지 않는다.

 

a = {1,2,3}
b =  {2,3,4}
print(a.union(b)) #합집합
print(a.intersection(b)) #교집합
print(a.difference(b)) #차집합
print(a.issubset(b)) #부분 집합 

 

 

 

 

반응형

'교육동영상 > 01. 딥러닝인공지능' 카테고리의 다른 글

06. 이미지 분석 tensorflow 2.0  (0) 2020.11.25
05. Tensorflow 2.0 Pytorch  (0) 2020.11.24
04. 인공지능에 대한 개념과 준비  (0) 2020.11.23
03. python 함수  (0) 2020.11.19
02. python 조건문, 반복문  (0) 2020.11.19

+ Recent posts