plt.imshow () изменяет вывод seaborn.countplot () - PullRequest
0 голосов
/ 22 мая 2018

Я пытаюсь запустить это ядро ​​kaggle в моей IDE Spyder.Поскольку я не пользуюсь ноутбуком Jupyter, я не могу использовать %matplotlib inline, однако я вполне уверен, что это не связано с моей проблемой ...

Я прочитал данные и нанес их на карту один разиспользуя seaborn, как показано в ядре, и получил ожидаемый результат:

# Load the data
train = pd.read_csv("./input/train.csv")
test = pd.read_csv("./input/test.csv")

Y_train = train["label"]

# Drop 'label' column
X_train = train.drop(labels = ["label"],axis = 1) 

# free some space
del train 

# print and plot digit count
g = sns.countplot(Y_train)
#print (Y_train.value_counts())

enter image description here

Я добавил следующие строки в ядре:

# Normalize the data
X_train = X_train / 255.0
test = test / 255.0

# Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1)
X_train = X_train.values.reshape(-1,28,28,1)
test = test.values.reshape(-1,28,28,1)

# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])
Y_train = to_categorical(Y_train, num_classes = 10)

# Set the random seed
random_seed = 2

# Split the train and the validation set for the fitting
X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed)

# Some examples
g = plt.imshow(X_train[0][:,:,0])

Вывод ядра такой:

enter image description here

, но по какой-то причине у меня это:

enter image description here

Я не понимаю, почему это меняет мое исходное изображение (теперь отображается только сжатое изображение) и не показывает цифровое изображение


Вот весь мой код (удалена строка %matplotlib inline и все (добавьте print s)):

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import itertools

from keras.utils.np_utils import to_categorical # convert to one-hot-encoding
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras.optimizers import RMSprop
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau

np.random.seed(2)
sns.set(style='white', context='notebook', palette='deep')

def system_info():
    print ('keras: %20s' % keras.__version__)
    print ('numpy: %20s' % np.__version__)
    print ('pandas: %19s' % pd.__version__)
    print ('seaborn: %18s' % sns.__version__)

# Load the data
train = pd.read_csv("./input/train.csv")
test = pd.read_csv("./input/test.csv")

Y_train = train["label"]

# Drop 'label' column
X_train = train.drop(labels = ["label"],axis = 1) 

# free some space
del train 

# print and plot digit count
g = sns.countplot(Y_train)               # <------ 1st plot. Works fine if the code ends here
#print (Y_train.value_counts())

# Check the data - check for missing data
#print(X_train.isnull().any().describe())
#print(test.isnull().any().describe())

# Normalize the data
X_train = X_train / 255.0
test = test / 255.0

# Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1)
X_train = X_train.values.reshape(-1,28,28,1)
test = test.values.reshape(-1,28,28,1)

# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])
Y_train = to_categorical(Y_train, num_classes = 10)

# Set the random seed
random_seed = 2

# Split the train and the validation set for the fitting
X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed)

# Some examples
g = plt.imshow(X_train[0][:,:,0])   # <------- 2nd plot. Removing this gives me back the bar table, but not the digit image expected

1 Ответ

0 голосов
/ 22 мая 2018

Вы строите один сюжет поверх другого.Попробуйте что-то вроде:

# beginning of your code here...
# open new figure and make first plot
plt.figure()
g = sns.countplot(Y_train) 
# rest of your code here
# open second figure and make second plot
plt.figure()
s = plt.imshow(X_train[0][:,:,0])
# showing your plots will show both plots separately
plt.show()
...