인공지능 공부 (5)
2025-05-02 00:37:33

ㅊKeras로 신경망을 작성하는 절차

model = tf.models.Sequential()

model.add(tf.keras.layers.Dense(units=2, input=(2,), activation='sigmoid'))
model.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))

model.compile(loss='mean_squared_error', optimizer=keras.optimizers.SGD(lr=0.3))

model.fit(X, y, batch_size=1, epochs=10000)

print(model.predict(X))

 

compile(optimizer, loss=None, metrics=None) : 훈련을 위해서 모델을 구성하는 메소드

fit(x=None, y=None, batch_size=None, epochs=1, verbose=1) : 훈련 메소드

evaluate(x=None, y=None) : 테스트 모드에서 모델의 손실 함수값과 측정 항목 값을 반환

predict(x, batch_size=None) : 입력 샘플에 대한 예측값을 생성

add(layer) : 레이어를 모델에 추가

 

Keras 사용 방법

1) Sequential 모델을 만들고 모델에 필요한 레이어를 1 추가하는 방법

 

model = Sequential()

 

model.add(Dense(units=2, input_shape=(2, ), activation='sigmoid'))

model.add(Dense(units=1, activation='sigmoid'))

 

2) Sequential 모델을 만들고 모델에 필요한 레이어를 추가하는 방법

 

model = Sequential()

 

model.add(Dense(units=2, input_shape=(2, ), activation='sigmoid'))

model.add(Dense(units=3, activation='sigmoid'))

model.add(Dense(units=1, activation='sigmoid'))

 

keras의 클래스들

  • 모델 : 하나의 신경망을 나타낸다
  • 레이어 : 신경망에서 하나의 층
  • 입력 데이터 : 텐서플로우 텐서 형식
  • 손실 함수 : 신경망의 출력과 정답 레이블 간의 차이를 측정하는 함수
  • 옵티마이저 : 학습을 수행하는 최적화 알고리즘. 학습률과 모멘텀을 동적으로 변경한다.

Input(shape, batch_size, name) : 입력을 받아서 케라스 텐서를 생성하는 객체

Dense(units, activation=None, use_bias=True, input_shape) : 유닛들이 전부 연결된 레이어

 

tf.keras.layers.Dense

완전 연결 계층 : 한 층의 모든 뉴런이 그 다음 층의 모든 뉴런과 연결된 상태

 

케라스 신경망 파라미터 -loss (손실 함수)

  • 회귀 
    • MeanSquaredError : 정답 레이블과 예측값 사이의 평균 제곱 오차를 계산
    • 분류에 사용되기도 함
  • 분류
    • BinaryCrossentropy : 정답 레이블과 예측 레이블 간의 교차 엔트로피 손실을 계산한다
      ex) 강아지, 강아지 아님
    • CatrgoryCrossentropy : 정갑 레이블과 예측 레이블 간의 교차 엔트로피 손실을 계산한다.
      ex) 강아지, 고양이, 호랑이. (정답 레이블은 원핫 인코딩으로 제공되어야 한다)
    • SparseCategoricalCrossentropy : 정답 레이블과 예측 레이블 간의 교차 엔트로피 손실을 계산한다.
      ex) 강아지, 고양이, 호랑이. (정답 레이블은 정수로 제공되어야 한다)

One hot encoding

3개의 class 강아지, 고양이, 호랑이 일 때, 한개의 1과 복수의 0으로 이루어진 벡터로 표현

  • 강아지 (0) => 1, 0, 0
  • 고양이 (1) => 0, 1, 0
  • 호랑이 (2) => 0, 0, 1
  •  

from tensorflow import keras
y_true = [80, 84, 92, 94]
y_pred = [70, 80, 90, 100]
mse=keras.losses.MSE
print(mse(y_true, y_pred).numpy())

 

 from tensorflow import keras
 y_true = [1, 0, 0, 1]
 y_pred = [0.7, 0.2, 0.3, 0.9]
 bce = keras.losses.BinaryCrossentropy()
 print(bce(y_true, y_pred).numpy())
 
 from tensorflow import keras
 y_true = [1, 0, 0, 1]
 y_pred = [0.6, 0.3, 0.4, 0.7]
 bce = keras.losses.BinaryCrossentropy()
 print(bce(y_true, y_pred).numpy())

 

 from tensorflow import keras
 y_true = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
 y_pred = [[0.6, 0.3, 0.1], [0.3, 0.6, 0.1], [0.7, 0.1, 0.2]]
 cce = keras.losses.CategoricalCrossentropy()
 print(cce(y_true, y_pred).numpy())
 
 from tensorflow import keras
 y_true = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
 y_pred = [[0.9, 0.0, 0.1], [0.2, 0.7, 0.1], [0.8, 0.1, 0.1]]
 cce = keras.losses.CategoricalCrossentropy()
 print(cce(y_true, y_pred).numpy())

 

keras 신경망 파라미터 : batch_size

  • 샘플을 몇 개 사용하여 가중치를 변경할 지 단위
  • batch_size가 너무 크면 학습 속도가 느려지고,
  • 너무 작으렴 학습 과정이 불안정해질 수 있음
  • 변수 (w, b)가 업데이트 되는 단위

1 epoch는 전체 샘플이 처리되는 기준

전체 샘플이 300개이고, batch_size가 30이면, 1 epoch동안 10번 가중치가 update됨

전체 샘플이 300개이고, batch_size가 10이면, 1 epoch동안 30번 가중치가 update됨

 

 

Metric : 측정 항목

Accuracy : 정확도. 예측값이 정답 레이블과 같은 횟수를 계산한다

MeanSquaredError : MSE

넘파이 배열

TensorFlow Dataset 객체 : 크기가 커서, 메모리에 한번에 적재될 수 없는 경우에 디스크 또는 분산 파일 시스템에서 스트리밍 될 수 있다.

파이썬 제너레이터 : 

 

 

import matplotlib.pyplot as plt
import tensorflow as tf

(train_images, train_labels), (test_images, test_labels)  = tf.keras.datasets.mnist.load_data()

print(train_images.shape)

print(train_labels)
print(test_images.shape)

plt.imshow(train_images[0], cmap="Greys")

model = tf.keras.models.Sequential()

model.add(tf.keras.layers.Dense(512, activation='relu', input_shape=(784,)))
model.add(tf.keras.layers.Dense(10, activation='sigmoid'))

model.compile(optimizer='rmsprop',
                loss='mse',
                metrics=['accuracy'])            

train_images = train_images.reshape((60000, 784))
train_images = train_images.astype('float32') / 255.0

test_images = test_images.reshape((10000, 784))
test_images = test_images.astype('float32') / 255.0

train_labels = tf.keras.utils.to_categorical(train_labels)
test_labels = tf.keras.utils.to_categorical(test_labels)

model.fit(train_images, train_labels, epochs=5, batch_size=256)

test_loss, test_acc = model.evaluate(test_images, test_labels)
print('테스트 정확도:', test_acc)

plt.show()

 

핵심 포인트 

유닛 수가 커질수록, 배치 사이즈가 작아질 수록 정확도는 올라간다!

하지만 학습 속도가 느려질 가능성이 있다..

 

범주형 데이터 처리

 

 

정수 인코딩

sklearn 라이브러리가 제공하는 Label Encoder 클래스를 사용

import numpy as np

X = np.array([['Korea', 44, 7200],
              ['Japan', 27, 4800],
              ['China', 30, 6100]])
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
X[:, 0] = labelencoder.fit_transform(X[:, 0])
print(X)
 
[['2' '44' '7200']
['1' '27' '4800']
['0' '30' '6100']]

 

import numpy as np

X=np.array([['Korea', 44, 7200],
            ['Japan', 27, 4800],
            ['China', 30, 6100]]) # Removed extra space before this line

from sklearn.preprocessing import OneHotEncoder # Added a missing space

onehotencoder= OneHotEncoder()
# 원하는열을뽑아서2차원배열로만들어서전달하여야한다.
XX = onehotencoder.fit_transform(X[:,0].reshape(-1,1)).toarray()
print(XX)
X = np.delete(X, [0], axis=1) # 0번째열삭제
X = np.concatenate((XX, X), axis = 1) # X와XX를붙인다.
print(X)
 
[[0. 0. 1.]
[0. 1. 0.]
[1. 0. 0.]]
[['0.0' '0.0' '1.0' '44' '7200']
['0.0' '1.0' '0.0' '27' '4800']
['1.0' '0.0' '0.0' '30' '6100']]
 

 

원 핫 인코딩

import numpy as np
X = np.array(['Korea', 'Japan', 'China'])

from sklearn.preprocessing import OneHotEncoder
onehotencoder = OneHotEncoder()
XX = onehotencoder.fit_transform(X.reshape(-1, 1)).toarray()
print(XX)
 
[[0. 0. 1.]
[0. 1. 0.]
[1. 0. 0.]]

 

케라스의 to_catetorical()

class_vector = [2, 6, 6, 1]

from tensorflow.keras.utils import to_categorical
output = to_categorical(class_vector, num_classes=7)
print(output)
 
[[0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 0. 1.]
[0. 1. 0. 0. 0. 0. 0.]]

아래 문자열 입력을 정수형으로 변경하고 print하는 code를 작성하시오

import numpy as np
X = np.array(['apple','grape','melon','orange'])

from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
XX = labelencoder.fit_transform(X)
print(XX)
 
[0 1 2 3]

 

아래 문자열 입력을 원 핫 인코딩으로 변경하고 print하는 code를 작성하시오.

import numpy as np
X = np.array(['apple','grape','melon','orange'])

from sklearn.preprocessing import OneHotEncoder
onehotencoder = OneHotEncoder()
XX = onehotencoder.fit_transform(X.reshape(-1, 1)).toarray()
print(XX)

[[1. 0. 0. 0.][0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]]

아래 class vector를 원 핫 인코딩으로 변경하고 print하는 code를 작성하시오.

from tensorflow import keras

class_vector =[8, 3, 2, 5]
from tensorflow.keras.utils import to_categorical
output = to_categorical(class_vector, num_classes=10)
print(output)
 
[[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]]

 

 

케라스 딥러닝 - 소프트 맥스

총헙아 1안 형태로 변환

 

 

케라스 신경망 실습 - 패션 아이템 분류

  • 이미지는 28*28 크기
  • 픽셀 값은 0과 255 사이
  • 레이블은 0부터 9 까지

model = models.Sequential()
model.add(layers.Flatten(input_shape=(28, 28)))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
 
model = models.Sequential()
model.add(layers.Flatten(input_shape=(28, 28)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))

 

판다스

  • 데이터를 머신러닝이나 시각화에 적절하도록 전처리 해주는 라이브러리
  • 자료구조 : 데이터 프레임
  • import pandas as pd

 

 

케라스 신경망 실습 - 타이타닉 생존자 예측

PassengerId : 각 승객의고유번호

Survived : 생존 여부(종속변수) •0 = 사망 •1 = 생존

Pclass : 객실 등급-승객의사회적, 경제적지위 •1st = Upper •2nd = Middle •3rd = Lower

Name : 이름 Sex : 성별 Age : 나이

SibSp : 동반한Sibling(형제자매)와

Spouse(배우자)의수 Parch : 동반한

Parent(부모) Child(자식)의 수

Ticket : 티켓의 고유넘버

Fare : 티켓의 요금

Cabin : 객실 번호

Embarked : 승선한 항 •C = Cherbourg •Q = Queenstown •S = Southampton

 

import numpy as np
import pandas as pd
import tensorflow as tf

# 데이터 세트를 읽어들인다.
train = pd.read_csv("train.csv", sep=',')
test = pd.read_csv("test.csv", sep=',')

# 필요없는 컬럼을 삭제한다.
train.drop(['SibSp', 'Parch', 'Ticket', 'Embarked', 'Name',\
        'Cabin', 'PassengerId', 'Fare', 'Age'], inplace=True, axis=1)
test.drop(['SibSp', 'Parch', 'Ticket', 'Embarked', 'Name',\
        'Cabin', 'PassengerId', 'Fare', 'Age'], inplace=True, axis=1)

# 결손치가 있는 데이터 행은 삭제한다.
train.dropna(inplace=True)
test.dropna(inplace=True)

# 기호를 수치로 변환한다.
for ix in train.index:
    if train.loc[ix, 'Sex']=="male":
       train.loc[ix, 'Sex']=1
    else:
       train.loc[ix, 'Sex']=0
for ix in test.index:
    if test.loc[ix, 'Sex']=="male":
       test.loc[ix, 'Sex']=1
    else:
       test.loc[ix, 'Sex']=0


# 2차원 배열을 1차원 배열로 평탄화한다.
target = np.ravel(train.Survived)


# 생존여부를 학습 데이터에서 삭제한다.
train.drop(['Survived'], inplace=True, axis=1)
train = train.astype(float)     # 최근 소스에서는 float형태로 형변환하여야
test = test.astype(float)     # 최근 소스에서는 float형태로 형변환하여야



# 케라스 모델을 생성한다.
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(16, activation='relu', input_shape=(2,)))
model.add(tf.keras.layers.Dense(8, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))

# 케라스 모델을 컴파일한다.
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
# 케라스 모델을 학습시킨다.
model.fit(train, target, epochs=30, batch_size=1, verbose=1)

 

 

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(16, activation='relu', input_shape=(2,)))
model.add(tf.keras.layers.Dense(8, activation='relu'))
model.add(tf.keras.layers.Dense(8, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))

0.7436
 
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(16, activation='relu', input_shape=(2,)))
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(8, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
 
0.8120

 

 

 

 

 

 

 

 

 

 

'인공지능 공부' 카테고리의 다른 글

인공지능 6주차  (0) 2025.04.08
인공지능 5주차  (0) 2025.04.01
인공지능 2차시  (0) 2025.03.18
인공지능  (0) 2025.03.18
2025-04-08 15:43:32

퍼셉트론 (Perceptron)

 

예제1) 입력이 (1, 0), w1 = 1, w2 = 1, b = -1.5 일 경우의 y의 값은? (계단 함수는위의 그림을 참조)

 

x1*w1 + x2*w2 + b = 1*1 + 0*1 -1.5 = -0.5

y = 0

 

예제 2) 입력이 (1, 1), w1 = 1, w2 = 1, b = -1.5 일 경우의 y의 값은?

 

x1*w1 + x2*w2 + b = 1*1 + 1*1 -1.5 = 0.5

y = 1

 

예제 2) 입력이 (1, 1), w1 = 1, w2 = 1, b = -0.5 일 경우의 y의 값은?

 

x1*w1 + x2*w2 + b = 1*1 + 1*1 -0.5 = 1.5

y = 1

 

퍼셉트론의 논린 연산

  • AND 연산
x1 x2 y
0 0 0
1 0 0
0 1 0
1 1 1

 

epsilon = 0.0000001

def perceptron(x1, x2):
  w1, w2, b = 1.0, 1.0, -1.5
  sum = x1 * w1 + x2 * w2 + b
  if sum > epsilon :
    return 1
  else :
    return 0

print(perceptron(0, 0))
print(perceptron(1, 0))
print(perceptron(0, 1))
print(perceptron(1, 1))
 
결과 : 0
          0
          0
          1

 

퍼셉트론도 scikit에서 학습이 가능하다!

from sklearn.linear_model import Perceptron
X = [[0, 0], [1, 0], [0, 1], [1, 1]]
y = [0, 0, 0, 1]

clf = Perceptron(tol=1e-3, random_state=0)

clf.fit(X, y)

print(clf.predict(X))
 
결과 : [0 0 0 1]

 

  • OR 연산
x1 x2 y
0 0 0
1 0 1
0 1 1
1 1 1
from sklearn.linear_model import Perceptron
X = [[0, 0], [1, 0], [0, 1], [1, 1]]
y = [0, 1, 1, 1]

clf = Perceptron(tol=1e-3, random_state=0)

clf.fit(X, y)

print(clf.predict(X))
 
결과 : [0, 1, 1, 1]

 

  • XOR 연산

 

x1 x2 y
0 0 0
1 0 1
0 1 1
1 1 0
from sklearn.linear_model import Perceptron
X = [[0, 0], [1, 0], [0, 1], [1, 1]]
y = [0, 1, 1, 0]

clf = Perceptron(tol=1e-3, random_state=0)

clf.fit(X, y)

print(clf.predict(X))
 
결과 : [0, 0, 0, 0]

 

퍼셉트론으로 XOR문제를 해결할 수 없다.

이를 해결하기 위해 다층 퍼셉트론이 필요하다.

 

행렬 곱셈

 

예제 1)

 

) 1*3 + 2*2 + 3*1 = 10

2) 1*2 + 2*0 + 3*3 = 11

3) 1*1 + 2*3 + 3*1 = 10

 

 

활성화 함수 

계단 함수는 입력 신호의 총합이 0을 넘으면 1을 출력하고, 그렇지 않으면 0을 출력하는 함수이다

 

  • 활성화 함수 (시그모이드)

  • 활성화 함수 (Rectifed Linear Unit function)

  • 활성화 함수 (Tanh)

 

 


다층 퍼셉트론 

입력층과 출력층 사이에 은닉층이 존재

 

 

순방향 패스

  • 입력 신호가 입력층 유닛에 가해지고, 이들 입력 신호가 은닉층을 통하여 출력층으로 전파되는 과정

역방향 패스

  • 신경망 내부의 가중치는 오차 역전파 방법을 사용해 수정

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'인공지능 공부' 카테고리의 다른 글

인공지능 9주차 (keras)  (1) 2025.05.02
인공지능 5주차  (0) 2025.04.01
인공지능 2차시  (0) 2025.03.18
인공지능  (0) 2025.03.18
2025-04-01 15:20:04

Scikit learn parameter

  • fit (X, y) 학습
    • X{array} of shape (n_samples, n_features)
  • Predict (X) : 예측
    • X{array} of shape (n_samples, n_features)

 

ex)

 

중요 포인트 : 학습 데이터의 수가 2차원, 학습 데이터의 특성이 1차원이다!


선형 회귀

  • 평균 제곱 오차(Mean Squared Error, MSE)
    오차의 합에 이어 각 X값의 평균 오차를 이용
    위에서 구한 갑을 n으로 나누면 오차의 합의 평균을 구할 수 있음

 

예제1)

 

MSE = ((70 - 80)^2 + (80 - 84)^2 + (90 - 92)^2 + (94 - 90)^2) / 4

         = (100 + 16 +  4 + 36) / 4

         = (156) / 4

         = 39

 

예제2)

 

MSE = ((78 - 80)^2 + (82 - 84)^2 + (88 - 92)^2 + (96 - 94)^2) / 4

         = (4 + 4 + 16 + 4) / 4

         = (28) / 4

         = 7

 

  • 오차 수정 : 경사 하강법
    • 그래프에서 오차를 작은 방향으로 이동. 미분 기울기 이용
    • 미분을 하면 순간 기울기가 구해짐
    • 미분값이 0인 지점이 오차가 가장 작은 지점
    • 미분 값으로 기울기를 구한 후, 기울기 반대 방향으로 학습률 * 기울기 만큼 움직임

    • 학습률이 낮을 때, 학습은 오래걸리지만, 정답을 찾을 확률은 높음
    • 학습률이 높을 때, 학습속도는 빠르지만, 정답을 놓칠 확률이 높음
  • 예제1

  • 예제2

x = 7,           y` = 10,        0.3 * 10 = 3

x = 4,           y` = 4,          0.3 * 4 = 1.2

'인공지능 공부' 카테고리의 다른 글

인공지능 9주차 (keras)  (1) 2025.05.02
인공지능 6주차  (0) 2025.04.08
인공지능 2차시  (0) 2025.03.18
인공지능  (0) 2025.03.18
2025-03-18 15:52:21

Numpy

  • 고성능의 수치 계산을 위한 라이브러리
  • 넘파이 라이브러리는 다차원 데이터 구조가 포함되어있다.
  • 넘파이는 데이터 전처리 및 다양한 수학적인 행렬 연산을 수행하는데 사용할 수 있다.
  • import numpy as np

 

딥러닝에서 넘파이가 중요한 이유

  • 학습 데이터는 2차원 행렬이나 3차원 행렬에 저장된다.

 

import numpy as np
a = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])

print(a.shape) # 배열의 형상
(3, 3)

print(a.ndim) # 배열의 차원 개수 
2

print(a.dtype) # 요소의 자료형
int64

print(a.itemsize) # 요소 한 개의 크기
8

print(a.size) # 전체 요소의 개수
9

np.zeros( (3, 4) ) # 내용을 0으로 3행 4열의 2차원 배열 생성
 array([[ 0.,  0.,  0.,  0.],
 [ 0.,  0.,  0.,  0.],
 [ 0.,  0.,  0.,  0.]])

np.ones( (3, 4) ) # 내용을 1로 3행 4열의 배열 생성
array([[1, 1, 1, 1],
 [1, 1, 1, 1],
 [1, 1, 1, 1]])

np.eyes(3) # 대각선 3열 3행의 3차원 배열 생성 후, 주대각선의 값만 1로, 나머지는 0으로 지정.
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])


np.arange(5) # 0부터 시작하여 5 이전까지의 값을 가지는 1차원 배열 생성
 array([0, 1, 2, 3, 4])
 
 np.arange(1, 6)
 array([1, 2, 3, 4, 5])
 
 np.arange(1, 10, 2) # 1부터 10 이전까지 값을 2씩 증가시키며 값을 채워넣음
 array([1, 3, 5, 7, 9])
 
 x = np.array([[1, 2], [3, 4]])
 y = np.array([[5, 6], [7, 8]])
 
 np.concatenate((x, y), axis=1)  # 두 배열끼리 차수가 맞는 배열만 합침
 array([1, 2, 5, 6],[3, 4, 7, 8])

 

예제

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print("문제 1 : ", a[1][2])  # 6
print("\n문제 2 : ", a.shape)  # (3, 3)
print("\n문제 3 : ", a.size)   # 9

print("\n문제 4 : \n", np.zeros((4, 2)))  # array([[0., 0.], [0., 0.], [0., 0.], [0., 0.]])

print("\n문제 5 : \n", np.arange(3, 12, 2))  # array([3, 5, 7, 9, 11])

x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[7, 8, 9], [10, 11, 12]])
print("\n문제 6 : \n", np.concatenate((x, y), axis=1))  # array([[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]])
print("\n문제 7 : \n", np.concatenate((x, y), axis=0))  # array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print("\n문제 8 : \n", np.vstack((x, y)))               # array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

a = np.arange(10)
print("\n문제 9 : \n", a.reshape(5, 2))  # array([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]])
print("\n문제 10 : \n", a.reshape(2, -1)) # array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])

a = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print("\n문제 11 : ", a.shape) 

a1 = a[np.newaxis, :]
print("\n문제 12 : \n", a1)       # array([[1, 2, 3, 4, 5, 6, 7, 8]])
print("\n문제 13 : ", a1.shape)   # (1, 8)

a2 = a[:, np.newaxis]
print("\n문제 14 : \n", a2)       # array([[1], [2], [3], [4], [5], [6], [7], [8]])
print("\n문제 15 : ", a2.shape)   # (8, 1)

'인공지능 공부' 카테고리의 다른 글

인공지능 9주차 (keras)  (1) 2025.05.02
인공지능 6주차  (0) 2025.04.08
인공지능 5주차  (0) 2025.04.01
인공지능  (0) 2025.03.18
2025-03-18 13:52:05

딥 러닝 ⊂ 머신 러닝 ⊂ 인공 지능 

 

  • 인공 지능 
    • 인간이 가진 지적 능력을 컴퓨터를 통해 구현하는 기술
  • 머신 러닝 
    • 데이터와 알고리즘을 통해 컴퓨터를 학습시켜 인공 지능의 성능을 향상 시키는 기술
  • 딥 러닝
    • 신경망을 이용한 머신 러닝 방법
    • 여러 층으로 이루어진 신경망을 사용

 

머신러닝의 종류

  • 지도 학습 : 입력과 출력(정답)을 학습 데이터로 제공
    • 회귀 : 입력과 출력이 모두 실수
      • Linear
      • polynomial
    • 판단트리
    • 랜덤 포리스트
    • 분류
  • 비지도 학습 : 정답이 주어지지 않고, 입력 데이터에서 패턴을 찾는 학습
    • 클러스터링
  • 강화 학습

 

머신 러닝의 과정 

  • 학습 데이터 모으기 ★
  • 학습 데이터 정제하기 ★
  • 모델 학습하기
  • 평가
  • 예측

'인공지능 공부' 카테고리의 다른 글

인공지능 9주차 (keras)  (1) 2025.05.02
인공지능 6주차  (0) 2025.04.08
인공지능 5주차  (0) 2025.04.01
인공지능 2차시  (0) 2025.03.18