Created
May 30, 2018 00:25
-
-
Save koshian2/efd43655e307c181dac7f8e51202d98e to your computer and use it in GitHub Desktop.
CIFAR-10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
from keras.datasets import cifar10 | |
from sklearn.svm import LinearSVC | |
import time | |
def convolution_filter(img): | |
# 縦方向のフィルター | |
prewitt_v = np.array([[-1,0,1], [-2,0,2], [-1,0,1]]) | |
# 横方向のフィルター | |
prewitt_h = np.array([[-1,-2,-1], [0,0,0], [1,2,1]]) | |
# カーネルサイズ | |
kernel_size = 3 | |
# 出力画像 | |
out_img = np.zeros((img.shape[0]-kernel_size+1, img.shape[1]-kernel_size+1, 3)) | |
for i in range(kernel_size-1, img.shape[0]-kernel_size+1): | |
for j in range(kernel_size-1, img.shape[1]-kernel_size+1): | |
# スライス | |
img_slice = img[(i-2):(i+1), (j-2):(j+1), 0:3] | |
# 畳み込み | |
conv_v = np.sum(img_slice * prewitt_v, axis=(1,2)) | |
conv_h = np.sum(img_slice * prewitt_h, axis=(1,2)) | |
# 代入 | |
out_img[i, j, :] = np.sqrt(conv_v**2 + conv_h**2) | |
return out_img | |
start_time = time.time() | |
# データの読み込み | |
(x_train_origin, y_train), (x_test_origin, y_test) = cifar10.load_data() | |
# Infを出さないように255で割る | |
x_train_origin = x_train_origin / 255 | |
x_test_origin = x_test_origin / 255 | |
# データ数 | |
m_train, m_test = x_train_origin.shape[0], x_test_origin.shape[0] | |
# 畳み込み変換用 | |
x_train = np.zeros((m_train, x_train_origin.shape[1]-2, x_train_origin.shape[2]-2, 3)) | |
x_test = np.zeros((m_test, x_test_origin.shape[1]-2, x_test_origin.shape[2]-2, 3)) | |
# 畳み込み | |
for i in range(m_train): | |
x_train[i, :, :, :] = convolution_filter(x_train_origin[i, :, :, :]) | |
x_train[i, :, :, :] = x_train[i, :, :, :] / np.max(x_train[i, :, :, :], axis=(0,1)) | |
for i in range(m_test): | |
x_test[i, :, :, :] = convolution_filter(x_test_origin[i, :, :, :]) | |
x_test[i, :, :, :] = x_test[i, :, :, :] / np.max(x_test[i, :, :, :], axis=(0,1)) | |
# ベクトル化 | |
x_train, x_test = x_train.reshape(m_train, -1), x_test.reshape(m_test, -1) | |
# ノルムで標準化 | |
x_train = x_train / np.linalg.norm(x_train, ord=2, axis=1, keepdims=True) | |
x_test = x_test / np.linalg.norm(x_test, ord=2, axis=1, keepdims=True) | |
# サポートベクトルマシン | |
svc = LinearSVC() | |
svc.fit(x_train, y_train) | |
print("Elapsed[s] : ", time.time() - start_time) | |
print("Train :", svc.score(x_train, y_train)) | |
print("Test :", svc.score(x_test, y_test)) | |
# デフォルト | |
#Elapsed[s] : 1282.1308102607727 | |
#Train : 0.26964 | |
#Test : 0.2153 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment