본문 바로가기

머신러닝 & 텐서플로 & 파이썬

Matplotlib 사용하기

반응형


ML/DEEP LEARNING 등을 스터디하다보면,

그래프를 통해서 결과를 확인해야 할 때가 많습니다.


이때 사용할 수 있는 matplotlib 을 소개하고자합니다.


https://matplotlib.org



python 에서 matplotlib을 사용하는 방법은 간단합니다.

아래 예제코드를 준비 했습니다.

import matplotlib.pyplot as plt



plt.figure()

plt.plot([1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,0])

plt.show()


print("hello")





cnn test 를 위해 작성한 코드


import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt




sess = tf.InteractiveSession()


image = np.array ([[[[1],[2],[3]],

                    [[4],[5],[6]],

                    [[7],[8],[9]]]], dtype=np.float32)


print(image.shape)

# visualization

plt.imshow(image.reshape(3,3), cmap='Greys')



print("image.shape", image.shape)

#weight = tf.constant([[[[1.]],[[1.]]],

#                      [[[1.]],[[1.]]]])


weight = tf.constant([[[[1.,10.,-1]],[[1.,10.,-1]]],

                      [[[1.,10.,-1]],[[1.,10.,-1]]]])

print("weight.shape", weight.shape)

conv2d = tf.nn.conv2d(image, weight, strides =[1,1,1,1], padding='SAME') # convolution - padding ='VALID'

conv2d_img = conv2d.eval()

print("conv2d_img.shape", conv2d_img.shape)


# visualization

conv2d_img = np.swapaxes(conv2d_img, 0,3)

for i , one_img in enumerate(conv2d_img):

        print(one_img.reshape(3,3))

        plt.subplot(1,3,i+1), plt.imshow(one_img.reshape(3,3), cmap='gray')


plt.show()


pool = tf.nn.max_pool(conv2d_img, ksize=[1,2,2,1],

                    strides=[1,1,1,1],padding='SAME')

print("pool", pool)




설치방법

그럼 설치 방법도 알아야 하는데요. https://matplotlib.org 에도 잘 설명이 되어있습니다.

제 개발 환경은 다음과 같습니다.

  - Ubuntu 14.04

  - python3.4

  - tensorflow 1.6

  - virtualenv


Ubuntu 환경에서 설치는 python3-matplotlib 를 하면 됩니다.


tensorflow 를 python3 ( 3.4) 버전에 서 사용하고 있기 때문에  python3-matplotlib를 설치 했습니다.

$ sudo apt-get install python3-matplotlib


python package 설치가 필요합니다.

(tensorflow)$ pip3 install --upgrade matplotlib

-- virtualenv를 사용하고 있어서 virtualenv 상에 matplotlib을 설치 하였습니다.