Tendon classification

##Library
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

from PIL import Image 

from sklearn.model_selection import train_test_split 

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
```

##Data
```python
files = os.listdir('.../pictures/')

print ('# of files: ', len(files))

size = 64

data = pd.DataFrame()
data['file'] = files
data['shop'] = data['file'].apply(lambda x: 1 if 'a' in str(x) else 0)
data['id'] = data['file'].apply(lambda x: x.replace('.jpg', ''))

path = '.../pictures/'
data['image'] = data['file'].apply(lambda x: 
                                   np.array(Image.open(path + str(x)).resize((size, size))))

data = data.drop('file', axis=1)

print ('shape: ', data.shape)

print (data['shop'].value_counts())

plt.figure(figsize = (5, 3))
sns.countplot(data['shop'])
plt.show()
```
![image.png](https://qiita-image-store.s3.amazonaws.com/0/254604/8846fcdb-b03e-6cfd-4fe4-eea31ad558f9.png)

![image.png](https://qiita-image-store.s3.amazonaws.com/0/254604/bdf229f2-fe3f-c768-4cf4-b3020ef2f253.png)

```python
x_train = np.array([im /255.0 for im in data['image']])
y_train = np.identity(2)[data['shop'].values].astype(float)

x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, 
                                                    test_size = 0.3, 
                                                    stratify=y_train)

print ('shape of x_train: ', x_train.shape)
print ('shape of y_train: ', y_train.shape)
print ('shape of x_val: ', x_val.shape)
print ('shape of y_val: ', y_val.shape)
```

![image.png](https://qiita-image-store.s3.amazonaws.com/0/254604/0382fd2c-312c-1e9d-fe7e-d5088b501ed3.png)


```python
index = np.random.randint(len(x_train))

print ('shop: ', np.argmax(y_train[index]))

plt.figure(figsize = (5, 3))
plt.imshow(x_train[index])
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.show()
```

![image.png](https://qiita-image-store.s3.amazonaws.com/0/254604/9c05bca4-3062-2ae5-4669-b023a75bc3fb.png)

![image.png](https://qiita-image-store.s3.amazonaws.com/0/254604/b02e2c31-80b8-3859-845e-cbdfc69f2804.png)

##Model
```python
# CNN
model = Sequential()
model.add(Conv2D(16, (3, 3), activation='relu', padding='same', 
                 input_shape=(size, size, 3)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(GlobalAveragePooling2D())
model.add(Dense(10, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(2, activation='softmax'))

model.summary()
```

![image.png](https://qiita-image-store.s3.amazonaws.com/0/254604/9bf283dd-9b3f-d604-4bb0-568dab67a07d.png)

```python
model.compile(loss='categorical_crossentropy', optimizer='adam', 
              metrics=['accuracy'])
```

##no data aumentaion
```python
history = model.fit(x_train, y_train, epochs=10, batch_size=16, 
                    validation_data=(x_val, y_val), verbose=2)
```

```python
plt.figure(figsize =(5,3))
plt.plot(history.history['loss'], marker='.', label='train')
plt.plot(history.history['val_loss'], marker='.', label='validation')
plt.title('Loss')
plt.grid(True)
plt.xlabel('epoch')
plt.ylabel('loss')
plt.legend(loc='best')
plt.show()

plt.figure(figsize =(5,3))
plt.plot(history.history['acc'], marker='.', label='train')
plt.plot(history.history['val_acc'], marker='.', label='validation')
plt.title('Accuracy')
plt.grid(True)
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.legend(loc='best')
plt.show()
```

![image.png](https://qiita-image-store.s3.amazonaws.com/0/254604/1c217a25-d8f8-94b9-f178-538178508a30.png)

##with data aumentaion
```python
from keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(
    horizontal_flip = False,
    vertical_flip = False,
    width_shift_range = 0.1,
    height_shift_range = 0.1,
    zoom_range = 0.1,
    rotation_range = 10,
    brightness_range=[0.8, 1.0],
    fill_mode='constant')

datagen.fit(x_train)

model.fit_generator(datagen.flow(x_train, y_train, batch_size=16), 
                    steps_per_epoch=len(x_train) / 16, epochs=10,
                    validation_data=(x_val, y_val), verbose=2)
```