Please wait ...
-
Day5: Neural Network Model
Activate function
Learning Analysis
Optimization Techniques
LAB
Mnist 실습
# 기본 라이브러리 불러오기
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
# 데이터 셋 불러오기
from tensorflow.keras.datasets.mnist import load_data
# 모델 설정용 라이브러리 불러오기
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import Adam
(train_x, train_y), (test_x, test_y) = load_data()
# 데이터 크기 확인하기
train_x.shape, train_y.shape
test_x.shape, test_y.shape
# 이미지 확인하기
from PIL import Image
img = train_x[0]
img1 = Image.fromarray(img, mode = 'L')
plt.imshow(img1)
train_y[0]
# 데이터 전처리
train_x1 = train_x.reshape(60000, -1) # 1차원 배열
test_x1 = test_x.reshape(10000, -1) # 1차원 배열
train_x2 = train_x1/255
test_x2 = test_x1/255
print(train_x2.shape) # (60000, 784)
print(test_x2.shape) # (10000, 784)
md = Sequential()
md.add(Dense(128, activation='relu', input_shape=(28*28,)))
md.add(Dropout(0.2))
md.add(Dense(64, activation='relu'))
md.add(Dropout(0.2))
md.add(Dense(10, activation='softmax'))
md.compile(loss='sparse_categorical_crossentropy', optimizer=Adam(learning_rate=0.0001), metrics=['acc'])
hist = md.fit(train_x2, train_y, epochs = 30, batch_size = 128, validation_split = 0.2)
acc = hist.history['acc']
val_acc = hist.history['val_acc']
epoch = np.arange(1, len(acc) +1)
plt.figure(figsize=(10,8))
plt.plot(epoch, acc, 'b', label='Training accuracy')
plt.plot(epoch, val_acc, 'r', label='Validation accuracy')
plt.title("Training and validation accuracy")
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
md.evaluate(test_x2, test_y)
weight = md.get_weights()
plt.plot(hist.history['loss'], label='loss')
plt.plot(hist.history['val_loss'], label='val_loss')
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# 기본 라이브러리 불러오기
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
# 데이터 셋 불러오기
from tensorflow.keras.datasets import cifar10
# 모델 설정용 라이브러리 불러오기
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import Adam
(train_x, train_y), (test_x, test_y) = cifar10.load_data()
# 데이터 크기 확인하기
print(train_x.shape) # (50000, 32, 32, 3)
print(train_y.shape) # (50000, 1)
print(test_x.shape) # (10000, 32, 32, 3)
print(test_y.shape) # (10000, 1)
# 이미지 확인하기
from PIL import Image
img = train_x[0]
img1 = Image.fromarray(img, mode = 'RGB')
plt.imshow(img1)
train_y[0]
# 데이터 전처리
train_x1 = train_x.reshape(50000, -1) # 1차원 배열
test_x1 = test_x.reshape(10000, -1) # 1차원 배열
train_x2 = train_x1/255
test_x2 = test_x1/255
print(train_x2.shape)
print(test_x2.shape)
md = Sequential()
md.add(Dense(512, activation='relu', input_shape=(3072,)))
md.add(Dropout(0.3))
md.add(Dense(256, activation='relu'))
md.add(Dropout(0.3))
md.add(Dense(128, activation='relu'))
md.add(Dropout(0.3))
md.add(Dense(10, activation='softmax'))
md.compile(loss='sparse_categorical_crossentropy', optimizer=Adam(learning_rate=0.0003), metrics=['acc'])
hist = md.fit(train_x2, train_y, epochs = 35, batch_size = 128, validation_split = 0.2)
acc = hist.history['acc']
val_acc = hist.history['val_acc']
epoch = np.arange(1, len(acc) +1)
plt.figure(figsize=(10,8))
plt.plot(epoch, acc, 'b', label='Training accuracy')
plt.plot(epoch, val_acc, 'r', label='Validation accuracy')
plt.title("Training and validation accuracy")
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
md.evaluate(test_x2, test_y)
weight = md.get_weights()
#print(weight)
plt.plot(hist.history['loss'], label='loss')
plt.plot(hist.history['val_loss'], label='val_loss')
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
-
Day5: Linear Model
(Mnist, Cifar_10) Dataset
1. 데이터셋 및 코드 개요
❓ Mnist 데이터셋이란?
손으로 쓴 숫자(0~9)를 인식하는 머신러닝 및 딥러닝 모델의 성능 평가를 위해 널리 사용되는 대표적인 이미지 데이터셋이다.
총 70,000개의 흑백(그레이스케일) 이미지로 이루어져 있으며, 60,000개는 학습용, 10,000개는 테스트용이다. 각 이미지는 28x28 픽셀 크기의 정사각형 형태이다.
❓ Cifar_10 데이터셋이란?
컴퓨터 비전 분야에서 이미지 분류 모델의 성능을 평가하기 위해 널리 사용되는 컬러 이미지 데이터셋이다.
총 60,000개의 컬러(RGB, 3채널) 이미지로 이루어져 있으며, 50,000개는 학습용, 10,000개는 테스트용이다. 각 이미지는 32x32 픽셀 크기이다.
2. 데이터 전처리 및 모델 구조
Mnist 데이터셋
데이터: (60000, 28, 28) 크기의 흑백 이미지, 라벨(0~9)
전처리: 이미지를 1차원(784)으로 변환 후 0~1 정규화
모델:
입력: Dense(3072)
출력층: Dense(10, softmax) (은닉층 없음)
손실함수: sparse_categorical_crossentropy
최적화: SGD
평가: 정확도(acc)
# Mnist 데이터 전처리
train_x1 = train_x.reshape(60000, -1) # 1차원 배열
test_x1 = test_x.reshape(10000, -1) # 1차원 배열
train_x2 = train_x1/255
test_x2 = test_x1/255
print(train_x2.shape) # (60000, 784)
print(test_x2.shape) # (10000, 784)
md = Sequential()
md.add(Dense(10, activation = 'softmax', input_shape = (28*28,)))
md.summary()
md.compile(loss='sparse_categorical_crossentropy', optimizer = 'sgd', metrics=['acc'])
hist = md.fit(train_x2, train_y, epochs = 30, batch_size = 64, validation_split = 0.2)
Cifar_10 데이터셋
데이터: (50000, 32, 32, 3) 크기의 컬러 이미지, 라벨(0~9)
전처리: 이미지를 1차원(3072)으로 변환 후 0~1 정규화
모델:
입력: Dense(3072)
출력층: Dense(10, softmax) (은닉층 없음)
손실함수: sparse_categorical_crossentropy
최적화: SGD
평가: 정확도(acc)
# Cifar_10 데이터 전처리
train_x1 = train_x.reshape(50000, -1) # 1차원 배열
test_x1 = test_x.reshape(10000, -1) # 1차원 배열
train_x2 = train_x1/255
test_x2 = test_x1/255
print(train_x2.shape) #(50000, 3072)
print(test_x2.shape) #(10000, 3072)
md = Sequential()
md.add(Dense(10, activation = 'softmax', input_shape = (32*32*3,)))
md.summary()
md.compile(loss='sparse_categorical_crossentropy', optimizer = 'sgd', metrics=['acc'])
hist = md.fit(train_x2, train_y, epochs = 30, batch_size = 128, validation_split = 0.2)
3. 코드 실행 및 결과 시각화
Mnist 데이터셋
Cifar_10 데이터셋
4. 두 코드의 주요 차이점
항목
MNIST 코드
CIFAR-10 코드
데이터 타입
흑백(1채널), 28x28
컬러(3채널), 32x32
입력 차원
784
3072
모델 구조
은닉층 ❌
은닉층 ❌
난이도
상대적으로 쉬움
상대적으로 어려움
분류 대상
손글씨 숫자(0~9)
10가지 사물
성능 기대치
높은 정확도 달성 용이
단순 모델로는 낮은 정확도
데이터 복잡성: CIFAR-10은 색상, 배경, 형태가 다양해 단순 신경망으로는 분류가 어렵고, MNIST는 단순한 흑백 숫자 이미지라 기본 신경망도 높은 성능을 보임.
5. CIFAR-10 정확도 향상을 위한 하이퍼파라미터 조정 방법
1. 은닉층 추가 및 크기 조정: Dense 레이어(은닉층)를 추가하고, 노드 수를 늘리면 더 복잡한 패턴을 학습
은닉층이 없는 구조에 Dense(100, activation=’softmax’)로 하면 100개의 클래스에 대한 확률을 내놓기 때문에, 10개 클래스 분류 문제에서는 올바른 결과 ❌
2. 활성화 함수 변경: 은닉층에 relu 등 비선형 활성화 함수를 적용해 모델 표현력을 높일 수 있다.
3. 배치 사이즈(batch size) 변경: 작은 배치는 더 빠른 업데이트, 큰 배치는 더 안정적인 학습을 유도
4. 에포크 수 조정: 더 오래 학습시키면 성능이 오를 수 있으나, 과적합에 주의
과적합은 모델이 학습 데이터의 노이즈나 세부적인 패턴까지 지나치게 학습하여, 새로운 데이터(테스트 데이터)에 대한 일반화 성능이 떨어지는 현상.
과적합된 모델은 학습 데이터에서는 높은 정확도를 보이지만, 테스트 데이터에서는 성능이 급격히 떨어진다.
❗과적합 방지법
조기 종료(Early Stopping): 검증 데이터의 성능이 더 이상 개선되지 않으면 학습 중단.
정규화(Regularization): L1, L2 정규화, 드롭아웃(Dropout) 등을 사용해 모델 복잡도 제어.
데이터 증강(Data Augmentation): 학습 데이터를 인위적으로 늘려 모델이 더 일반화되도록 한다.
적절한 에포크 수 설정: 검증 성능이 최고일 때 학습을 멈추는 것이 이상적이다.
6. 결론
정확도가 너무 낮은 것은 모델 구조의 한계 때문이다. 하이퍼파라미터 조정만으로는 근본적인 해결이 어렵다. 은닉층을 추가하거나 CNN을 사용하는 것이 좋을 것 같다.
-
-
Day4: Deep Learning
Compare Perceptron, Multi Layer perceptron XOR Gate
1. 네트워크 구조의 차이
Perceptron
- Single layer : 입력층과 출력층만 존재하며, 입력값에 가중치와 바이어스를 더한 뒤 바로 출력
self.weights = np.zeros(input_size)
self.bias = 0
- 활성화 함수: 계단함수와 같은 단순한 함수를 사용한다.
Multi Layer Perceptron
- Multi layer : 입력층, 은닉층, 출력층으로 구성된다.
self.w1 = np.random.randn(input_size, hidden_size)
self.b1 = np.zeros(hidden_size)
self.w2 = np.random.randn(hidden_size, output_size)
self.b2 = np.zeros(output_size)
- 활성화 함수: sigmoid, tanh 등 연속적이고 미분 가능한 함수 사용. 각 층마다 적용한다.
2. 순전파 연산의 차이
Perceptron
- 입력층 -> 출력층
linear_output = np.dot(x, self.weights) + self.bias
return self.activation(linear_output)
Multi Layer Perceptron
- 입력층 -> 은닉층 -> 출력층
self.z1 = np.dot(x, self.w1) + self.b1
self.a1 = sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.w2) + self.b2
self.a2 = sigmoid(self.z2)
return self.a2
3. 가중치 업데이트 방식의 차이
Perceptron
- 단순 업데이트
update = self.lr * (target - prediction)
self.weights += update * x1
self.bias += update
Multi Layer Perceptron
- 역전파(Backpropagation) 사용
출력층 오차를 은닉층까지 전파하여 모든 가중치/바이어스를 미분값(gradient)으로 업데이트한다
# 출력층 오차
error_output = self.a2 - y
delta2 = error_output * sigmoid_diff(self.z2)
# 은닉층 오차
error_hidden = np.dot(self.w2, delta2)
delta1 = error_hidden * sigmoid_diff(self.z1)
# 가중치 업데이트
self.w2 -= self.lr * np.outer(self.a1, delta2)
self.b2 -= self.lr * delta2
self.w1 -= self.lr * np.outer(x, delta1)
self.b1 -= self.lr * delta1
4. 문제 해결 능력의 차이
Perceptron
- 퍼셉트론: XOR처럼 선형적으로 구분 불가능한 문제는 절대 풀 수 없음. 단일 직선(혹은 평면)만으로 데이터를 나눈다.
Multi Layer Perceptron
- MLP: 은닉층의 비선형 변환 덕분에 XOR 등 복잡한 패턴도 학습 가능. 실제로 MLP 코드는 XOR 문제를 성공적으로 해결할 수 있음
5. 코드 예시
Perceptron
출력층 오차만 사용
class Perceptron:
def __init__(self, input_size, ...):
self.weights = np.zeros(input_size)
self.bias = 0
def predict(self, x):
return self.activation(np.dot(x, self.weights) + self.bias)
def train(self, X, y):
Multi Layer Perceptron
여러 층 순전파
역전파로 모든 층 가중치 업데이트
class MLP:
def __init__(self, input_size, hidden_size, output_size, ...):
self.w1 = np.random.randn(input_size, hidden_size)
self.b1 = np.zeros(hidden_size)
self.w2 = np.random.randn(hidden_size, output_size)
self.b2 = np.zeros(output_size)
def forward(self, x):
def backward(self, x, y):
6. 요약
구분
퍼셉트론
MLP
층 구조
입력-출력(단일층)
입력-은닉-출력(다층)
가중치/바이어스
1개(입력→출력)
2세트(입력→은닉, 은닉→출력)
순전파
한 번의 선형 연산+활성화
여러 층의 선형 연산+비선형 활성화 반복
학습 방식
출력층 오차로 단순 업데이트
역전파로 모든 층의 가중치/바이어스 업데이트
활성화 함수
계단함수/시그모이드(단순)
시그모이드/탄젠트 등(비선형, 미분 가능)
문제 해결력
선형 문제만 해결(XOR 불가)
비선형 문제(XOR 등) 해결 가능
-
Day3: Perceptron_MLP
#
📌 Perceptron이란?
1957년 프랭크 로젠브라트가 고안한 최초의 인공신경망 모델 중 하나.
생물학적 뉴런을 수학적으로 모델링한 인공 뉴런으로, 여러 입력 신호를 받아 각각의 가중치를 곱한 후 이를 합산하여, 활성화 함수를 통해 단일 신호를 출력한다.
퍼셉트론의 출력은 신호 유무 (1 또는 0)로 표현된고, 이진 분류 문제 해결에 효과적이다.
📝 Perceptron AND_GATE 실습
🔍 AND 게이트 모델 훈련 후 결과 확인
import numpy as np
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, input_size, lr=0.1, epochs=10):
self.weights = np.zeros(input_size)
self.bias = 0
self.lr = lr
self.epochs = epochs
self.errors = []
def activation(self, x):
return np.where(x >= 0, 1, 0)
def predict(self, x):
linear_output = np.dot(x, self.weights) + self.bias
return self.activation(linear_output)
def train(self, X, y):
for epoch in range(self.epochs):
total_error = 0
for x1, target in zip(X, y):
prediction = self.predict(x1)
update = self.lr * (target - prediction)
self.weights += update * x1
self.bias += update
total_error += int(update != 0)
self.errors.append(total_error)
print(f"Epoch {epoch+1}/{self.epochs}, Errors: {total_error}")
# AND 게이트 데이터
X_and = np.array([[0,0],[0,1],[1,0],[1,1]])
y_and = np.array([0,0,0,1])
# 퍼셉트론 모델 훈련
ppn_and = Perceptron(input_size=2)
ppn_and.train(X_and, y_and)
# 예측 결과 확인
print("\nAND Gate Test:")
for x in X_and:
print(f"Input: {x}, Predicted Output: {ppn_and.predict(x)}")
💡 출력 결과
🔍 AND 게이트 결정 경계 시각화
from matplotlib.colors import ListedColormap
def plot_decision_boundary(X, y, model):
cmap_light = ListedColormap(['#FFAAAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#0000FF'])
h = .02 # mesh grid 간격
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.figure(figsize=(8, 6))
plt.contourf(xx, yy, Z, cmap=cmap_light)
# 실제 데이터 포인트 표시
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,
edgecolor='k', s=100, marker='o')
plt.xlabel('Input 1')
plt.ylabel('Input 2')
plt.title('Perceptron Decision Boundary')
plt.show()
# AND 게이트 결정 경계 시각화
plot_decision_boundary(X_and, y_and, ppn_and)
💡 출력 결과
🔍 오류 시각화
plt.figure(figsize=(8, 5))
plt.plot(range(1, len(ppn_and.errors) + 1), ppn_and.errors, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of Errors')
plt.title('Perceptron Learning Error Over Epochs (AND Gate)')
plt.grid(True)
plt.show()
💡 출력 결과
📝 Perceptron OR_GATE 실습
🔍 OR 게이트 모델 훈련 후 결과 확인
import numpy as np
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, input_size, lr=0.1, epochs=10):
self.weights = np.zeros(input_size)
self.bias = 0
self.lr = lr
self.epochs = epochs
self.errors = []
def activation(self, x):
return np.where(x >= 0, 1, 0)
def predict(self, x):
linear_output = np.dot(x, self.weights) + self.bias
return self.activation(linear_output)
def train(self, X, y):
for epoch in range(self.epochs):
total_error = 0
for x1, target in zip(X, y):
prediction = self.predict(x1)
update = self.lr * (target - prediction)
self.weights += update * x1
self.bias += update
total_error += int(update != 0)
self.errors.append(total_error)
print(f"Epoch {epoch+1}/{self.epochs}, Errors: {total_error}")
# OR 게이트 데이터
X_or = np.array([[0,0],[0,1],[1,0],[1,1]])
y_or = np.array([0,1,1,1])
# 퍼셉트론 모델 훈련
ppn_or = Perceptron(input_size=2)
ppn_or.train(X_or, y_or)
# 예측 결과 확인
print("\nOR Gate Test:")
for x in X_or:
print(f"Input: {x}, Predicted Output: {ppn_or.predict(x)}")
💡 출력 결과
🔍 OR 게이트 결정 경계 시각화
from matplotlib.colors import ListedColormap
def plot_decision_boundary(X, y, model):
cmap_light = ListedColormap(['#FFAAAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#0000FF'])
h = .02 # mesh grid 간격
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.figure(figsize=(8, 6))
plt.contourf(xx, yy, Z, cmap=cmap_light)
# 실제 데이터 포인트 표시
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,
edgecolor='k', s=100, marker='o')
plt.xlabel('Input 1')
plt.ylabel('Input 2')
plt.title('Perceptron Decision Boundary')
plt.show()
# OR 게이트 결정 경계 시각화
plot_decision_boundary(X_or, y_or, ppn_or)
💡 출력 결과
🔍 오류 시각화
plt.figure(figsize=(8, 5))
plt.plot(range(1, len(ppn_or.errors) + 1), ppn_or.errors, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of Errors')
plt.title('Perceptron Learning Error Over Epochs (OR Gate)')
plt.grid(True)
plt.show()
💡 출력 결과
📝 Perceptron NAND_GATE 실습
🔍 NAND 게이트 모델 훈련 후 결과 확인
import numpy as np
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, input_size, lr=0.1, epochs=10):
self.weights = np.zeros(input_size)
self.bias = 0
self.lr = lr
self.epochs = epochs
self.errors = []
def activation(self, x):
return np.where(x >= 0, 1, 0)
def predict(self, x):
linear_output = np.dot(x, self.weights) + self.bias
return self.activation(linear_output)
def train(self, X, y):
for epoch in range(self.epochs):
total_error = 0
for x1, target in zip(X, y):
prediction = self.predict(x1)
update = self.lr * (target - prediction)
self.weights += update * x1
self.bias += update
total_error += int(update != 0)
self.errors.append(total_error)
print(f"Epoch {epoch+1}/{self.epochs}, Errors: {total_error}")
# NAND 게이트 데이터
X_nand = np.array([[0,0],[0,1],[1,0],[1,1]])
y_nand = np.array([1,1,1,0])
# 퍼셉트론 모델 훈련
ppn_nand = Perceptron(input_size=2)
ppn_nand.train(X_nand, y_nand)
# 예측 결과 확인
print("\nNAND Gate Test:")
for x in X_nand:
print(f"Input: {x}, Predicted Output: {ppn_nand.predict(x)}")
💡 출력 결과
🔍 NAND 게이트 결정 경계 시각화
from matplotlib.colors import ListedColormap
def plot_decision_boundary(X, y, model):
cmap_light = ListedColormap(['#FFAAAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#0000FF'])
h = .02 # mesh grid 간격
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.figure(figsize=(8, 6))
plt.contourf(xx, yy, Z, cmap=cmap_light)
# 실제 데이터 포인트 표시
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,
edgecolor='k', s=100, marker='o')
plt.xlabel('Input 1')
plt.ylabel('Input 2')
plt.title('Perceptron Decision Boundary')
plt.show()
# NAND 게이트 결정 경계 시각화
plot_decision_boundary(X_nand, y_nand, ppn_nand)
💡 출력 결과
🔍 오류 시각화
plt.figure(figsize=(8, 5))
plt.plot(range(1, len(ppn_or.errors) + 1), ppn_or.errors, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of Errors')
plt.title('Perceptron Learning Error Over Epochs (OR Gate)')
plt.grid(True)
plt.show()
💡 출력 결과
📝 Perceptron XOR_GATE 실습
🔍 XOR 게이트 모델 훈련 후 결과 확인
import numpy as np
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, input_size, lr=0.1, epochs=10):
self.weights = np.zeros(input_size)
self.bias = 0
self.lr = lr
self.epochs = epochs
self.errors = []
def activation(self, x):
return np.where(x >= 0, 1, 0)
def predict(self, x):
linear_output = np.dot(x, self.weights) + self.bias
return self.activation(linear_output)
def train(self, X, y):
for epoch in range(self.epochs):
total_error = 0
for x1, target in zip(X, y):
prediction = self.predict(x1)
update = self.lr * (target - prediction)
self.weights += update * x1
self.bias += update
total_error += int(update != 0)
self.errors.append(total_error)
print(f"Epoch {epoch+1}/{self.epochs}, Errors: {total_error}")
# XOR 게이트 데이터
X_xor = np.array([[0,0],[0,1],[1,0],[1,1]])
y_xor = np.array([0,1,1,0])
# 퍼셉트론 모델 훈련
ppn_xor = Perceptron(input_size=2)
ppn_xor.train(X_xor, y_xor)
# 예측 결과 확인
print("\nXOR Gate Test:")
for x in X_xor:
print(f"Input: {x}, Predicted Output: {ppn_xor.predict(x)}")
💡 출력 결과
🔍 XOR 게이트 결정 경계 시각화
from matplotlib.colors import ListedColormap
def plot_decision_boundary(X, y, model):
cmap_light = ListedColormap(['#FFAAAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#0000FF'])
h = .02 # mesh grid 간격
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.figure(figsize=(8, 6))
plt.contourf(xx, yy, Z, cmap=cmap_light)
# 실제 데이터 포인트 표시
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,
edgecolor='k', s=100, marker='o')
plt.xlabel('Input 1')
plt.ylabel('Input 2')
plt.title('Perceptron Decision Boundary')
plt.show()
# XOR 게이트 결정 경계 시각화
plot_decision_boundary(X_xor, y_xor, ppn_xor)
💡 출력 결과
🔍 오류 시각화
plt.figure(figsize=(8, 5))
plt.plot(range(1, len(ppn_or.errors) + 1), ppn_or.errors, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of Errors')
plt.title('Perceptron Learning Error Over Epochs (OR Gate)')
plt.grid(True)
plt.show()
💡 출력 결과
🚨 단층 Perceptron의 한계점
XOR GATE는 퍼셉트론으로 학습이 되지 않는 문제가 발생하였다.
퍼셉트론은 직선 하나로 ●와 ○를 나눌 수 있어야 학습이 된다.
하지만 XOR은 직선 하나로는 절대 ●와 ○를 나눌 수 없다.
-
Basic Operation
📝 학습목표
OpenCV(Open Source Computer Vision Library)를 활용하여 이미지/비디오 처리하기
1. 이미지 Read & Write
📂 이미지 파일 준비
import numpy as np
import cv2
img = cv2.imread("image.jpg")
cv2.namedWindow("image", cv2.WINDOW_NORMAL)
print(img.shape)
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.imwrite("output.png", img)
cv2.destroyAllWindows()
💡 출력 결과
2. 색상 채널 분리와 색공간 변환
📂 이미지 파일 준비
import numpy as np
import cv2
color = cv2.imread("strawberry.jpg", cv2.IMREAD_COLOR)
print(color.shape)
height, width, channels = color.shape
cv2.imshow("Original Image", color)
r,g,b = cv2.split(color)
rgb_split = np.concatenate((r,g,b), axis=1)
cv2.imshow("RGB Channels", rgb_split)
hsv = cv2.cvtColor(color, cv2.COLOR_RGB2HSV)
h,s,v = cv2.split(hsv)
hsv_split = np.concatenate((h,s,v),axis=1)
cv2.imshow("Split HSV", hsv_split)
cv2.waitKey(0)
cv2.imwrite("hsv2rgb_split.png", hsv_split)
💡 출력 결과
3. 이미지 일부 영역 자르기, 크기 바꾸기, 회전하기
📂 이미지 파일 준비
import numpy as np
import cv2
img = cv2.imread("image.jpg")
print(img.shape) # 0,100
cropped = img[0:220, 185:385] #220, 200, 3
print(cropped.shape)
resized = cv2.resize(cropped, (400,200))
print(resized.shape)
rotated_90 = cv2.rotate(resized, cv2.ROTATE_90_CLOCKWISE)
#rotated_180 = cv2.rotate(image, cv2.ROTATE_180)
#rotated_270 = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
cv2.imshow("Origin", img)
cv2.imshow("Cropped image", cropped)
cv2.imshow("Resized image", resized)
cv2.imshow("Rotated 90 image", rotated_90)
cv2.waitKey(0)
cv2.destroyAllWindows()
💡 출력 결과
cropped
resized
rotated_90
4. 원본 색상 반전시키기
📂 이미지 파일 준비
import numpy as np
import cv2
src = cv2.imread("output.png", cv2.IMREAD_COLOR)
dst = cv2.bitwise_not(src)
cv2.imshow("src", src)
cv2.imshow("dst", dst)
cv2.waitKey()
cv2.destroyAllWindows()
💡 출력 결과
5. 임계값 기준으로 이진화시키기
📂 이미지 파일 준비
import cv2
src = cv2.imread("image.jpg", cv2.IMREAD_COLOR)
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
ret, dst = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
cv2.imshow("dst", dst)
cv2.waitKey()
cv2.destroyAllWindows()
💡 출력 결과
6. 이미지 흐리게(블러) 처리
📂 이미지 파일 준비
import cv2
src = cv2.imread("image.jpg", cv2.IMREAD_COLOR)
dst = cv2.blur(src, (9, 9), anchor=(-1, -1), borderType=cv2.BORDER_DEFAULT)
cv2.imshow("dst", dst)
cv2.waitKey()
cv2.destroyAllWindows()
💡 출력 결과
7. 세 가지 대표적인 엣지(경계) 검출 알고리즘
📂 이미지 파일 준비
import cv2
src = cv2.imread("image.jpg", cv2.IMREAD_COLOR)
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
sobel = cv2.Sobel(gray, cv2.CV_8U, 1, 0, 3)
cv2.imshow("sobel", sobel)
laplacian = cv2.Laplacian(gray, cv2.CV_8U, ksize=3)
cv2.imshow("laplacian", laplacian)
canny = cv2.Canny(gray, 100, 200)
cv2.imshow("canny", canny)
cv2.waitKey()
cv2.destroyAllWindows()
💡 출력 결과
sobel
laplacian
canny
8. 컬러 이미지의 BGR(Blue, Green, Red) 채널을 분리 후 채널 순서를 바꿔서 이미지 합치기
📂 이미지 파일 준비
import numpy as np
import cv2
src = cv2.imread("image.jpg", cv2.IMREAD_COLOR)
#b,g,r = cv2.split(src)
b = src[:, :, 0]
g = src[:, :, 1]
r = src[:, :, 2]
inverse = cv2.merge((r,g,b))
cv2.imshow("b", b)
cv2.imshow("g", g)
cv2.imshow("r", r)
cv2.imshow("inverse", inverse)
cv2.waitKey()
cv2.destroyAllWindows()
💡 출력 결과
B
G
R
inverse
9. 컬러 이미지의 BGR(Blue, Green, Red) 채널을 분리 후 Red 채널만 0(검정색)
📂 이미지 파일 준비
import numpy as np
import cv2
src = cv2.imread("bgr.png", cv2.IMREAD_COLOR)
b = src[:, :, 0]
g = src[:, :, 1]
r = src[:, :, 2]
height, width, channel = src.shape
zero = np.zeros((height, width, 1), dtype=np.uint8)
bgz = cv2.merge((b, g, zero))
cv2.imshow("b", b)
cv2.imshow("g", g)
cv2.imshow("r", r)
cv2.imshow("bgz", bgz)
cv2.waitKey()
cv2.destroyAllWindows()
💡 출력 결과
B
G
R
bgz
10. 동영상에서 원하는 장면을 이미지로 캡처하기
📂 동영상 파일 준비
import numpy as np
import cv2
import os
save_dir = "SON"
os.makedirs(save_dir, exist_ok=True)
cap = cv2.VideoCapture("output.mp4")
img_idx = 1
while cap.isOpened():
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
continue
height, width = frame.shape[:2]
small_frame = cv2.resize(frame, (width // 2, height // 2), interpolation=cv2.INTER_AREA)
cv2.imshow("Frame", small_frame)
key = cv2.waitKey(80)
if key & 0xFF == ord('q'):
break
if key & 0xFF == ord('c'):
while True:
filename = f"{img_idx:03d}.jpg"
filepath = os.path.join(save_dir, filename)
if not os.path.exists(filepath):
cv2.imwrite(filepath, small_frame)
print(f"Saved {filepath}")
img_idx += 1
break
else:
img_idx += 1
cap.release()
cv2.destroyAllWindows()
💡 출력 결과
11. 다양한 OpenCV 그리기 함수 사용해보기
import numpy as np
import cv2
cap = cv2.VideoCapture(5)
circle_centers = []
def draw_circle(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
circle_centers.append((x, y))
cv2.namedWindow("Camera")
cv2.setMouseCallback("Camera", draw_circle)
topLeft = (50, 50)
bottomRight = (300, 300)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cv2.line(frame, topLeft, bottomRight, (0, 255, 0), 3)
cv2.rectangle(frame,
[pt+30 for pt in topLeft], [pt-30 for pt in bottomRight], (255, 0, 255), 3)
font = cv2.FONT_ITALIC
cv2.putText(frame, 'me',
[pt+40 for pt in bottomRight], font, 2, (255, 0, 255), 5)
for center in circle_centers:
cv2.circle(frame, center, 30, (255, 255, 0), 3)
cv2.imshow("Camera", frame)
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
💡 출력 결과
12. 실시간 카메라 영상 위에 글자 출력하고 트랙바로 굵기, 크기, 색상 조절하기
import numpy as np
import cv2
cap = cv2.VideoCapture(4)
#initial
topLeft = (100, 100)
bold = 0
font_size = 1
r, g, b = 0, 255, 255
def on_bold_trackbar(value):
global bold
bold = value
def on_fontsize_trackbar(value):
global font_size
font_size = max(1, value)
def on_r(val):
global r
r = val
def on_g(val):
global g
g = val
def on_b(val):
global b
b = val
cv2.namedWindow("Camera")
cv2.createTrackbar("bold", "Camera", bold, 10, on_bold_trackbar)
cv2.createTrackbar("font size", "Camera", font_size, 10, on_fontsize_trackbar)
cv2.createTrackbar('R', 'Camera', 0, 255, on_r)
cv2.createTrackbar('G', 'Camera', 255, 255, on_g)
cv2.createTrackbar('B', 'Camera', 255, 255, on_b)
while cap.isOpened():
ret, frame = cap.read()
if ret is False:
print("Can't receive frame (stream end?). Exiting . . .")
break
# Text
cv2.putText(frame, 'TEXT', topLeft, cv2.FONT_HERSHEY_SIMPLEX, font_size, (b, g, r), 1 + bold)
# Display
cv2.imshow("Camera", frame)
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
💡 출력 결과
13. 실시간 카메라 영상 위에 한글 출력하고 트랙바로 굵기, 크기, 색상 조절하기
import numpy as np
import cv2
from PIL import ImageFont, ImageDraw, Image
cap = cv2.VideoCapture(4)
topLeft = (100, 100)
bold = 0
font_size = 10
r, g, b = 0, 255, 255
def on_bold_trackbar(value):
global bold
bold = value
def on_fontsize_trackbar(value):
global font_size
font_size = max(10, value * 5)
def on_r(val):
global r
r = val
def on_g(val):
global g
g = val
def on_b(val):
global b
b = val
cv2.namedWindow("Camera")
cv2.createTrackbar("bold", "Camera", bold, 10, on_bold_trackbar)
cv2.createTrackbar("font size", "Camera", font_size//5, 10, on_fontsize_trackbar)
cv2.createTrackbar('R', 'Camera', 0, 255, on_r)
cv2.createTrackbar('G', 'Camera', 255, 255, on_g)
cv2.createTrackbar('B', 'Camera', 255, 255, on_b)
font_path = "NanumGothic.ttf"
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting . . .")
break
img_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img_pil)
font = ImageFont.truetype(font_path, font_size)
text = 'LEE 은성'
# Bold 효과: 여러 번 겹쳐 그리기
for dx in range(-bold, bold+1):
for dy in range(-bold, bold+1):
draw.text((topLeft[0]+dx, topLeft[1]+dy), text, font=font, fill=(r, g, b, 0))
frame = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR)
cv2.imshow("Camera", frame)
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
💡 출력 결과
-
Day1: AI Algotirhm and Structure
Von Neumann Architecture
폰 노이만 구조
폰 노이만 병목 현상
하버드 구조
파이프라인
1. 폰 노이만 구조
폰 노이만 구조란?
폰 노이만 구조가 등장하기 전까지는 하드와이어드 프로그래밍 방식을 사용했다. 폰 노이만 구조가 등장하면서, 프로그램 내장 방식을 사용하게 되었고, 특징은 명령어와 데이터가 같은 메모리 공간에 저장되고 순차적으로 실행된다.
하드와이어드 프로그래밍 방식 : 폰 노이만 구조가 등장하기 전까지는 계산을 할 때마다 손으로 직접 진공관의 회로 스위치를 조정하여 새 입력을 처리하는 하드웨어 프로그램 방식
폰 노이만 구조의 주요 구성 요소
중앙처리장치(CPU)
메모리(Memory)
입출력장치(In.Out Device)
버스 시스템(Bus)
폰 노이만 구조의 동작 원리
폰 노이만 구조의 컴퓨터는 명령어 실행 사이클을 반복 동작한다.
명령어 인출(Fetch): 메모리에서 명령어를 가져온다.
명령어 해석(Decode): 메모리에서 가져온 명령어가 어떤 명령어인지 해석한다.
명령어 실행(Execute): 명령어를 실행한다.
메모리 연산(Data Memory): 명령어 수행을 위해 메모리와 데이터 레지스터 간의 데이터 이동을 처리
저장(WriteBack): 연산 결과를 메모리에 저장한다.
//사진 넣기
2. 폰 노이만 구조의 병목 현상
폰 노이만 구조의 단점
폰노이만 구조의 가장 치명적인 단점은 폰노이만 병목현상이다.
단일 버스 구조
명령어와 데이터가 같은 버스를 공유하기 때문에 나타나는 현상이다. CPU는 한번에 명령어 또는 데이터를 가져올 수 있기 때문에 동시에 불가능하다.
메모리 벽
CPU의 성능은 기하급수적으로 발전했지만, 메모리의 속도가 그에 미치지 못해 이 속도 격차가 CPU의 대기 시간을 늘려 CPU의 제 성능을 발휘하지 못한다.
순차적 처리
명령어가 순차적으로 실행이 되는데, 이러한 처리 방식은 갈수록 데이터 종류가 다양해지고, 대규모 병렬 연산이 필요한 현대 사회에서는 비효율적이다.
폰 노이만 구조의 병목현상이 미치는 영향
상대적으로 메모리보다 빠른 CPU가 대부분의 시간을 메모리를 기다리게 되므로 시스템의 성능 저하로 이어진다. (CPU의 유후 시간 증가)
데이터가 CPU와 메모리를 왔다갔다하는 것이 전력 소모가 크다.
-> 신호 전이(Transition)에 따른 전력 소모
버스에서 데이터가 0->1, 1->0으로 바뀔 때마다 transition이 발생 -> transition의 횟수가 많아질수록 전력 소모 증가
-> 캐패시터 충전과 방전
버스의 선로는 캐패시터 역할을 함 -> 데이터가 변경 될 때마다 커패시터를 충방전하게 된다 -> 더 빠른 스위칭을 위해서는 높은 과도 전류가 필요하게 되어 전력 소모가 증가하게 된다.
3. 하버드 구조
하버드 구조란?
폰 노이만 구조에서는 하나의 버스 시스템에서 데이터와 명령어가 이동했지만, 하버드 구조는 명령어와 데이터를 물리적으로 분리된 메모리에 저장하고 접근하는 구조이다.
폰 노이만 구조 vs 하버드 구조
하버드 구조에서는 폰 노이만 구조와 달리 명령어를 메모리로부터 읽는 것과 데이터를 메모리로부터 읽는 것을 동시에 할 수 있다.
하버드 구조는 병렬 처리를 통한 성능 향상이 가능하다. 현재 명령어를 처리함과 동시에 다음 명령어를 읽을 수 있다. (파이프라인)
하버드 구조 적용 사례
디지털 신호 처리기 (DSP)에서 주로 사용한다. 실시간 데이터 처리가 중요한 프로세서로, 하버드 구조의 병렬 메모리 접근 능력이 더 높은 메모리 대역폭을 제공하기 때문이다.
메모리 대역폭이란?
-> 단위 시간당 전송 가능한 데이터의 양, 초당 얼마나 많은 비트(bit)를 주고받을 수 있는 지.
-> CPU가 명령어를 인출하면서 동시에 데이터 메모리에서 연산에 필요한 데이터를 읽어올 수 있다. 즉, 두 개의 독립된 명령어 버스, 데이터 버스를 통해 동시에 전송이 가능하므로 전체 메모리 대역폭을 두배로 사용 가능.
-
-
-
-
CMOS Inverter
CMOS Inverter Simulation with Synopsys Custom Compiler
This guide walks through creating, simulating, and analyzing a CMOS inverter schematic using Synopsys Custom Compiler and PrimeWave.
1. Library and Cell Setup
Create a new library:
New → Library
Set attributes:
Name: Library name
Technology: Select tech library
Create a new CellView:
File → New → CellView
Configure:
Cell Name: Inverter
View Name: schematic
Design Settings:
Options → Design → Configure:
Snap Spacing (X,Y): Grid spacing
Solder Dot Size: Connection point size
Fat Wire Width: Thick wire width
Default Net Prefix: Signal prefix
2. Schematic Design
Add Components:
Use the Add tool (I=Instance, W=Wire, L=Label, P=Pin):
Add
I
W
L
P
Instance
Wire
Label
Pin
CMOS Inverter Schematic:
Place PMOS and NMOS transistors
Connect to VDD (top) and VSS (bottom)
Add input (VIN) and output (VOUT) pins
CMOS Schematic
Component Properties:
Select components → Press q → Configure:
Transistor dimensions (W/L)
Net connections
3. Symbol Creation
Generate Symbol:
Pin Arrangement:
Position
Pin Name
Left
VIN
Right
VOUT
Top
VDD
Bottom
VSS
Adjust Pins
Final Inverter Symbol:
Not symbol
4. Test Schematic Setup
Create Testbench:
Add Components:
Inverter symbol (Instance)
Ground (GND)
Voltage source (VDC)
Configure Voltage Sources:
Component
Property
Value
VDD
Voltage
1.8V
VIN
Voltage
DC variable
VSS
Voltage
0V
5. Simulation with PrimeWave
Launch PrimeWave:
Set Model Files:
Configure Simulation:
Model Section: Select (e.g., FF)
Variables: Copy from Design → Set VIN=0 (설정하지 않으면 simulation이 안나올 수 있다)
Simulation Engine: PrimeSim HSPICE
Run Analysis:
Setup → Analyses
Analysis Type: dc
DC Analysis → Design Variable
Variable Name, Sweep Type: VIN
Start, Stop, Step Size: e.g., 0, 1.8, 0.01
Run Simulation:
Results:
NOT WaveView
6. Troubleshooting
Schematic Lock Issue:
Delete lock file: *sch.oa.cdslck
Advanced Configuration:
Variable overrides
Simulator options
Key Notes
VIN Initialization: Must be set to 0V for DC sweep
Model Selection: Use correct technology corner (e.g., FF)
Port Connections: Verify VDD/VSS connections in test schematic
This structured guide ensures reproducible CMOS inverter simulation with clear visualization at each step.
-
-
Manage blog comments with Giscus
Giscus is a free comments system powered without your own database. Giscus uses the Github Discussions to store and load associated comments based on a chosen mapping (URL, pathname, title, etc.).
To comment, visitors must authorize the giscus app to post on their behalf using the GitHub OAuth flow. Alternatively, visitors can comment on the GitHub Discussion directly. You can moderate the comments on GitHub.
Prerequisites
Create a github repo
You need a GitHub repository first. If you gonna use GitHub Pages for hosting your website, you can choose the corresponding repository (i.e., [userID].github.io)
The repository should be public, otherwise visitors will not be able to view the discussion.
Turn on Discussion feature
In your GitHub repository Settings, make sure that General > Features > Discussions feature is enabled.
Activate Giscus API
Follow the steps in Configuration guide. Make sure the verification of your repository is successful.
Then, scroll down from the manual page and choose the Discussion Category options. You don’t need to touch other configs.
Copy _config.yml
Now, you get the giscus script. Copy the four properties marked with a red box as shown below:
Paste those values to _config.yml placed in the root directory.
# External API
giscus_repo: "[ENTER REPO HERE]"
giscus_repoId: "[ENTER REPO ID HERE]"
giscus_category: "[ENTER CATEGORY NAME HERE]"
giscus_categoryId: "[ENTER CATEGORY ID HERE]"
None
· 2024-02-03
-
Classic Literature #2: Don Quixote
About the book
Author: Miguel de Cervantes
Original title: El ingenioso hidalgo don Quixote de la Mancha
Country: Spain
Genre: Novel
Publication date:
1605 (Part One)
1615 (Part Two)
Chapter I.
In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income. The rest of it went in a doublet of fine cloth and velvet breeches and shoes to match for holidays, while on week-days he made a brave figure in his best homespun. He had in his house a housekeeper past forty, a niece under twenty, and a lad for the field and market-place, who used to saddle the hack as well as handle the bill-hook. The age of this gentleman of ours was bordering on fifty; he was of a hardy habit, spare, gaunt-featured, a very early riser and a great sportsman. They will have it his surname was Quixada or Quesada (for here there is some difference of opinion among the authors who write on the subject), although from reasonable conjectures it seems plain that he was called Quexana. This, however, is of but little importance to our tale; it will be enough not to stray a hair’s breadth from the truth in the telling of it.
You must know, then, that the above-named gentleman whenever he was at leisure (which was mostly all the year round) gave himself up to reading books of chivalry with such ardour and avidity that he almost entirely neglected the pursuit of his field-sports, and even the management of his property; and to such a pitch did his eagerness and infatuation go that he sold many an acre of tillageland to buy books of chivalry to read, and brought home as many of them as he could get. But of all there were none he liked so well as those of the famous Feliciano de Silva’s composition, for their lucidity of style and complicated conceits were as pearls in his sight, particularly when in his reading he came upon courtships and cartels, where he often found passages like “the reason of the unreason with which my reason is afflicted so weakens my reason that with reason I murmur at your beauty;” or again, “the high heavens, that of your divinity divinely fortify you with the stars, render you deserving of the desert your greatness deserves.” Over conceits of this sort the poor gentleman lost his wits, and used to lie awake striving to understand them and worm the meaning out of them; what Aristotle himself could not have made out or extracted had he come to life again for that special purpose. He was not at all easy about the wounds which Don Belianis gave and took, because it seemed to him that, great as were the surgeons who had cured him, he must have had his face and body covered all over with seams and scars. He commended, however, the author’s way of ending his book with the promise of that interminable adventure, and many a time was he tempted to take up his pen and finish it properly as is there proposed, which no doubt he would have done, and made a successful piece of work of it too, had not greater and more absorbing thoughts prevented him.
Many an argument did he have with the curate of his village (a learned man, and a graduate of Siguenza) as to which had been the better knight, Palmerin of England or Amadis of Gaul. Master Nicholas, the village barber, however, used to say that neither of them came up to the Knight of Phoebus, and that if there was any that could compare with him it was Don Galaor, the brother of Amadis of Gaul, because he had a spirit that was equal to every occasion, and was no finikin knight, nor lachrymose like his brother, while in the matter of valour he was not a whit behind him. In short, he became so absorbed in his books that he spent his nights from sunset to sunrise, and his days from dawn to dark, poring over them; and what with little sleep and much reading his brains got so dry that he lost his wits. His fancy grew full of what he used to read about in his books, enchantments, quarrels, battles, challenges, wounds, wooings, loves, agonies, and all sorts of impossible nonsense; and it so possessed his mind that the whole fabric of invention and fancy he read of was true, that to him no history in the world had more reality in it. He used to say the Cid Ruy Diaz was a very good knight, but that he was not to be compared with the Knight of the Burning Sword who with one back-stroke cut in half two fierce and monstrous giants. He thought more of Bernardo del Carpio because at Roncesvalles he slew Roland in spite of enchantments, availing himself of the artifice of Hercules when he strangled Antaeus the son of Terra in his arms. He approved highly of the giant Morgante, because, although of the giant breed which is always arrogant and ill-conditioned, he alone was affable and well-bred. But above all he admired Reinaldos of Montalban, especially when he saw him sallying forth from his castle and robbing everyone he met, and when beyond the seas he stole that image of Mahomet which, as his history says, was entirely of gold. To have a bout of kicking at that traitor of a Ganelon he would have given his housekeeper, and his niece into the bargain.
In short, his wits being quite gone, he hit upon the strangest notion that ever madman in this world hit upon, and that was that he fancied it was right and requisite, as well for the support of his own honour as for the service of his country, that he should make a knight-errant of himself, roaming the world over in full armour and on horseback in quest of adventures, and putting in practice himself all that he had read of as being the usual practices of knights-errant; righting every kind of wrong, and exposing himself to peril and danger from which, in the issue, he was to reap eternal renown and fame. Already the poor man saw himself crowned by the might of his arm Emperor of Trebizond at least; and so, led away by the intense enjoyment he found in these pleasant fancies, he set himself forthwith to put his scheme into execution.
The first thing he did was to clean up some armour that had belonged to his great-grandfather, and had been for ages lying forgotten in a corner eaten with rust and covered with mildew. He scoured and polished it as best he could, but he perceived one great defect in it, that it had no closed helmet, nothing but a simple morion. This deficiency, however, his ingenuity supplied, for he contrived a kind of half-helmet of pasteboard which, fitted on to the morion, looked like a whole one. It is true that, in order to see if it was strong and fit to stand a cut, he drew his sword and gave it a couple of slashes, the first of which undid in an instant what had taken him a week to do. The ease with which he had knocked it to pieces disconcerted him somewhat, and to guard against that danger he set to work again, fixing bars of iron on the inside until he was satisfied with its strength; and then, not caring to try any more experiments with it, he passed it and adopted it as a helmet of the most perfect construction.
He next proceeded to inspect his hack, which, with more quartos than a real and more blemishes than the steed of Gonela, that “tantum pellis et ossa fuit,” surpassed in his eyes the Bucephalus of Alexander or the Babieca of the Cid. Four days were spent in thinking what name to give him, because (as he said to himself) it was not right that a horse belonging to a knight so famous, and one with such merits of his own, should be without some distinctive name, and he strove to adapt it so as to indicate what he had been before belonging to a knight-errant, and what he then was; for it was only reasonable that, his master taking a new character, he should take a new name, and that it should be a distinguished and full-sounding one, befitting the new order and calling he was about to follow. And so, after having composed, struck out, rejected, added to, unmade, and remade a multitude of names out of his memory and fancy, he decided upon calling him Rocinante, a name, to his thinking, lofty, sonorous, and significant of his condition as a hack before he became what he now was, the first and foremost of all the hacks in the world.
Having got a name for his horse so much to his taste, he was anxious to get one for himself, and he was eight days more pondering over this point, till at last he made up his mind to call himself “Don Quixote,” whence, as has been already said, the authors of this veracious history have inferred that his name must have been beyond a doubt Quixada, and not Quesada as others would have it. Recollecting, however, that the valiant Amadis was not content to call himself curtly Amadis and nothing more, but added the name of his kingdom and country to make it famous, and called himself Amadis of Gaul, he, like a good knight, resolved to add on the name of his, and to style himself Don Quixote of La Mancha, whereby, he considered, he described accurately his origin and country, and did honour to it in taking his surname from it.
So then, his armour being furbished, his morion turned into a helmet, his hack christened, and he himself confirmed, he came to the conclusion that nothing more was needed now but to look out for a lady to be in love with; for a knight-errant without love was like a tree without leaves or fruit, or a body without a soul. As he said to himself, “If, for my sins, or by my good fortune, I come across some giant hereabouts, a common occurrence with knights-errant, and overthrow him in one onslaught, or cleave him asunder to the waist, or, in short, vanquish and subdue him, will it not be well to have some one I may send him to as a present, that he may come in and fall on his knees before my sweet lady, and in a humble, submissive voice say, ‘I am the giant Caraculiambro, lord of the island of Malindrania, vanquished in single combat by the never sufficiently extolled knight Don Quixote of La Mancha, who has commanded me to present myself before your Grace, that your Highness dispose of me at your pleasure’?” Oh, how our good gentleman enjoyed the delivery of this speech, especially when he had thought of some one to call his Lady! There was, so the story goes, in a village near his own a very good-looking farm-girl with whom he had been at one time in love, though, so far as is known, she never knew it nor gave a thought to the matter. Her name was Aldonza Lorenzo, and upon her he thought fit to confer the title of Lady of his Thoughts; and after some search for a name which should not be out of harmony with her own, and should suggest and indicate that of a princess and great lady, he decided upon calling her Dulcinea del Toboso—she being of El Toboso—a name, to his mind, musical, uncommon, and significant, like all those he had already bestowed upon himself and the things belonging to him.
-
Classic Literature #1: Romeo and Juliet
About the book
Author: William Shakespeare
Country: England
Genre: Shakespearean tragedy
Publication date: 1597
Synopsis
The prologue of Romeo and Juliet calls the title characters “star-crossed lovers”—and the stars do seem to conspire against these young lovers.
Romeo is a Montague, and Juliet a Capulet. Their families are enmeshed in a feud, but the moment they meet—when Romeo and his friends attend a party at Juliet’s house in disguise—the two fall in love and quickly decide that they want to be married.
A friar secretly marries them, hoping to end the feud. Romeo and his companions almost immediately encounter Juliet’s cousin Tybalt, who challenges Romeo. When Romeo refuses to fight, Romeo’s friend Mercutio accepts the challenge and is killed. Romeo then kills Tybalt and is banished. He spends that night with Juliet and then leaves for Mantua.
Juliet’s father forces her into a marriage with Count Paris. To avoid this marriage, Juliet takes a potion, given her by the friar, that makes her appear dead. The friar will send Romeo word to be at her family tomb when she awakes. The plan goes awry, and Romeo learns instead that she is dead. In the tomb, Romeo kills himself. Juliet wakes, sees his body, and commits suicide. Their deaths appear finally to end the feud.
-
My personal Online Library
What is Lorem Ipsum?
This is an example post ‘<’. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ‘Content here, content here’, making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ‘lorem ipsum’ will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of “de Finibus Bonorum et Malorum” (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, “Lorem ipsum dolor sit amet..”, comes from a line in section 1.10.32.
The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from “de Finibus Bonorum et Malorum” by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don’t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn’t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
-
-
Touch background to close