# 0. PyTorh / Pandas 불러오기
import torch
import pandas as pd
print('현재 PyTorch 버전:', torch.__version__)
# 1. 데이터 불러오기
df = pd.read_csv('/content/drive/MyDrive/Ecommerce Customers.csv'); df
# 2. 데이터 정보 확인
df.info()
df['Yearly Amount Spent'] # 타깃
# 3. 데이터 시각화
import seaborn as sns
import matplotlib.pyplot as plt
# sns.pairplot (연속변수 산점도 -> 변수별 관계 확인)
sns.pairplot(df)
plt.show()
# sns.regplot (회귀선)
sns.regplot(x = 'Time on App', y = "Yearly Amount Spent", data = df)
plt.show()
# sns.displot (히스토그램)
sns.displot(df['Yearly Amount Spent'])
plt.show()
<뉴럴 네트워크 설계>
1. X(Input), Y(target, 실제값) 행렬 정의
2. 모델 설정 (가중치 초기화 및 계산식)
3. 옵티마이저 설정
4. 반복 학습 → 최종 가중치 도출
- 4-1) 예측값 계산
- 4-2) 손실함수 값 계산
- 4-3) 옵티마이저 학습
- 4-4) 가중치 시각화
X(Input), Y(target, 실제값) 행렬 정의
# X
matrix = df.iloc[:,3:7].copy() # 특성 행렬 설정 (50*4)
input = torch.Tensor(matrix.values) # 학습 입력값 텐서 설정
# Y
Y = torch.Tensor(df['Yearly Amount Spent']).reshape(-1,1) # (50*1)
모델 설정 ( 가중치 초기화 및 계산식 )
EX. 선형회귀
# 가중치 & 편향벡터 초기화
W1 = torch.rand((4,1), requires_grad = True) # (4*1)
b1 = torch.rand(1, requires_grad = True)
# 예측값 계산
outputs = torch.matmul(input, W1) + b1
# torch.nn 불러오기
import torch.nn
# 선형회귀 클래스 설정 (모델 클래스)
class LinearRegression(torch.nn.Module):
def __init__(self):
super().__init__()
self.layer1 = torch.nn.Linear(4, 1)
def forward(self, x):
x = self.layer1(x)
return x
# LinearRegression 모델 설정
model = LinearRegression()
class NeuralNetwork(torch.nn.Module):
def __init__(self):
super().__init__()
self.layer1 = torch.nn.Linear(4, 10)
self.layer2 = torch.nn.Linear(10, 1)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
return x
model = NeuralNetwork()
반복학습 → 최종 가중치 도출
epochs = 1000
for epoch in range(epochs):
# 1) 예측값 계산
# 2) 손실함수 값 계산
# 3) 옵티마이저 학습
# 4) 가중치 시각화
# 가중치 값 확인
w1 = list(model.parameters())[0]
b1 = list(model.parameters())[1]
class NeuralNetworkWithActivation(torch.nn.Module):
def __init__(self):
super().__init__()
self.layer1 = torch.nn.Linear(4, 10)
self.relu = torch.nn.ReLU()
self.layer2 = torch.nn.Linear(10, 1)
def forward(self, x):
x = self.relu(self.layer1(x))
x = self.layer2(x)
return x
class NeuralNetworkWithSigmoid(torch.nn.Module):
def __init__(self):
super().__init__()
self.layer1 = torch.nn.Linear(4, 10)
self.sigmoid = torch.nn.Sigmoid()
self.layer2 = torch.nn.Linear(10, 1)
def forward(self, x):
x = self.layer1(x)
x = self.sigmoid(x)
x = self.layer2(x)
return x
# MSE 손실 함수 설정
loss = torch.mean(torch.pow(y - outputs, 2))
# torch.nn.MSELoss
criterion = torch.nn.MSELoss()
loss = criterion(outputs, y)
# 옵티마이저 설정
optimizer = torch.optim.Adam([W1, b1], lr=0.1)
optimizer = torch.optim.Adam(model.parameters(), lr = 0.1)
# 옵티마이저 학습
optimizer.zero_grad()
loss.backward()
optimizer.step()