CT(Iamages using Contrast Classification CNN with Keras(tensorflow))¶
- RI / CT 를 찍게 되면 조영제(Contrast)를 사용하게 되는데 사용한 그림인지 아닌지 구분하는 코드.
In [66]:
import dicom # dicom file handling library
import numpy as np # matrix tools
import matplotlib.pyplot as plt # for basic plots
import seaborn as sns # for nicer plots
import pandas as pd
import re
from skimage.io import imread
import os
import keras
In [67]:
%matplotlib inline
In [6]:
os.listdir('data/dicom_dir')[:5]
Out[6]:
In [164]:
PathDicom = 'data/dicom_dir'
lstFilesDCM = []
for dirName, subdirList, fileList in os.walk(PathDicom):
for filename in fileList:
if ".dcm" in filename.lower():
lstFilesDCM.append(os.path.join(PathDicom,filename))
In [165]:
len(lstFilesDCM)
Out[165]:
Get ref file¶
In [166]:
RefDs = dicom.read_file(lstFilesDCM[0])
- Load dimensions based on the number of rows, columns, and slices (along the Z axis)
In [167]:
RefDs.pixel_array.shape
Out[167]:
In [168]:
ConstPixelDims = (len(lstFilesDCM), int(RefDs.Rows), int(RefDs.Columns))
In [169]:
ConstPixelDims
Out[169]:
In [172]:
# The array is sized based on 'ConstPixelDims'
ArrayDicom = numpy.zeros(ConstPixelDims, dtype=RefDs.pixel_array.dtype)
print(ArrayDicom.shape)
# loop through all the DICOM files
for filenameDCM in lstFilesDCM:
# read the file
ds = dicom.read_file(filenameDCM)
# store the raw image data
ArrayDicom[lstFilesDCM.index(filenameDCM), :, :] = ds.pixel_array
In [173]:
pyplot.imshow(ArrayDicom[20,:,:])
Out[173]:
In [174]:
check_contrast = re.compile(r'ID_([\d]+)_AGE_\d+_CONTRAST_([\d])_CT.dcm')
In [175]:
label = []
id_list = []
for image in lstFilesDCM:
id_list.append(check_contrast.findall(image)[0][0])
label.append(check_contrast.findall(image)[0][1])
label_list = pd.DataFrame(label,id_list)
In [176]:
len(ArrayDicom)
Out[176]:
Split Data to Train, Test¶
In [177]:
from sklearn.model_selection import train_test_split
In [178]:
ArrayDicom = np.expand_dims(ArrayDicom,0)
In [179]:
ArrayDicom = ArrayDicom.reshape((100,512,512,1))
In [214]:
ArrayDicom = ArrayDicom[:,::3,::3]
In [241]:
X_train, X_test, y_train, y_test = train_test_split(ArrayDicom, label_list, test_size=0.2, random_state=0)
In [242]:
X_train.shape
Out[242]:
In [243]:
n_train, width, height,depth = X_train.shape
n_test,_,_,_ = X_test.shape
In [244]:
input_shape = (width,height,depth)
input_shape
Out[244]:
In [245]:
input_train = X_train.reshape((n_train, width,height,depth))
input_train.shape
input_train.astype('float32')
input_train = input_train / np.max(input_train)
input_train.max()
Out[245]:
In [246]:
input_test = X_test.reshape(n_test, *input_shape)
input_test.astype('float32')
input_test = input_test / np.max(input_test)
In [247]:
output_train = keras.utils.to_categorical(y_train, 2)
output_test = keras.utils.to_categorical(y_test, 2)
output_train[5]
Out[247]:
Network¶
In [248]:
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.optimizers import Adam
from keras.layers import Conv2D, MaxPooling2D
In [249]:
model2 = Sequential()
model2.add(Conv2D(50, (5, 5), activation='relu', input_shape=input_shape))
# 32개의 4x4 Filter 를 이용하여 Convolutional Network생성
model2.add(MaxPooling2D(pool_size=(4, 4), strides=(2,2))) # 3x3 Maxpooling
model2.add(Conv2D(30, (4, 4), activation='relu', input_shape=input_shape))
model2.add(Conv2D(50, (3, 3), activation='relu', input_shape=input_shape))
model2.add(MaxPooling2D(pool_size=(2, 2))) # 2x2 Maxpooling
model2.add(Flatten()) # 쭉풀어서 Fully Connected Neural Network를 만든다.
model2.add(Dense(2, activation='softmax'))
In [250]:
model2.summary()
In [251]:
batch_size = 30
epochs = 50
In [252]:
model2.compile(loss='categorical_crossentropy',
optimizer=Adam(),
metrics=['accuracy'])
In [253]:
history = model2.fit(input_train, output_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(input_test, output_test))
In [254]:
score = model2.evaluate(input_test, output_test, verbose=0)
score
Out[254]:
'BIGDATA > Kaggle[데이터 분석]' 카테고리의 다른 글
[kaggle] QVC Challenge, QVC(e-commerce) 어떠한 물건이 언제 어디서 팔릴 것 인가? (0) | 2017.09.04 |
---|---|
[kaggle] NASA Astronauts, 1959-Present, 어떠한 미국인 우주비행사가 우주에서 많은 시간을 보냈는가? (0) | 2017.09.04 |
[kaggle] School Alcohol holic problem, 어떠한 학생들이 알콜중독에 빠지는가? (0) | 2017.09.04 |
[Kaggle] IMDB 5000 Movies, 어떠한 요소가 영화 평점에 영향을 미치는가? (0) | 2017.09.04 |