可视化不出现在Tensorflow-PyCharm IDE中
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了可视化不出现在Tensorflow-PyCharm IDE中相关的知识,希望对你有一定的参考价值。
我正在使用PyCharm Community Edition和Python 3.7。通过Anaconda,我安装了Tensorflow机器学习包。
我正在关注回归教程here,但我的输出有限。只有数字结果显示在输出控制台上 - 而不是视觉效果。我知道plot_history(history)
语句应该导致输出控制台上的可视化 - 但是,它没有显示。如何在PyCharm上进行相应的可视化?
这是我的main.py
:
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow import keras
import numpy as np
import pandas as pd
print(tf.__version__)
boston_housing = keras.datasets.boston_housing
(train_data, train_labels), (test_data, test_labels) = boston_housing.load_data()
# Shuffle the training set
order = np.argsort(np.random.random(train_labels.shape))
train_data = train_data[order]
train_labels = train_labels[order]
# output some data
print("Training set: {}".format(train_data.shape)) # 404 examples, 13 features
print("Testing set: {}".format(test_data.shape)) # 102 examples, 13 features
column_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD',
'TAX', 'PTRATIO', 'B', 'LSTAT']
df = pd.DataFrame(train_data, columns=column_names)
df.head()
print(train_labels[0:10]) # Display first 10 entries
# Test data is *not* used when calculating the mean and std
# Normalize data
mean = train_data.mean(axis=0)
std = train_data.std(axis=0)
train_data = (train_data - mean) / std
test_data = (test_data - mean) / std
print(train_data[0]) # First training sample, normalized
def build_model():
model = keras.Sequential([
keras.layers.Dense(64, activation=tf.nn.relu,
input_shape=(train_data.shape[1],)),
keras.layers.Dense(64, activation=tf.nn.relu),
keras.layers.Dense(1)
])
optimizer = tf.train.RMSPropOptimizer(0.001)
model.compile(loss='mse',
optimizer=optimizer,
metrics=['mae'])
return model
model = build_model()
model.summary()
# Display training progress by printing a single dot for each completed epoch
class PrintDot(keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs):
if epoch % 100 == 0: print('')
print('.', end='')
EPOCHS = 500
# Store training stats
history = model.fit(train_data, train_labels, epochs=EPOCHS,
validation_split=0.2, verbose=0,
callbacks=[PrintDot()])
import matplotlib.pyplot as plt
def plot_history(history):
plt.figure()
plt.xlabel('Epoch')
plt.ylabel('Mean Abs Error [1000$]')
plt.plot(history.epoch, np.array(history.history['mean_absolute_error']),
label='Train Loss')
plt.plot(history.epoch, np.array(history.history['val_mean_absolute_error']),
label='Val loss')
plt.legend()
plt.ylim([0, 5])
plot_history(history)
[loss, mae] = model.evaluate(test_data, test_labels, verbose=0)
print("Testing set Mean Abs Error: ${:7.2f}".format(mae * 1000))
test_predictions = model.predict(test_data).flatten()
plt.scatter(test_labels, test_predictions)
plt.xlabel('True Values [1000$]')
plt.ylabel('Predictions [1000$]')
plt.axis('equal')
plt.xlim(plt.xlim())
plt.ylim(plt.ylim())
_ = plt.plot([-100, 100], [-100, 100])
error = test_predictions - test_labels
plt.hist(error, bins=50)
plt.xlabel("Prediction Error [1000$]")
_ = plt.ylabel("Count")
这是我的输出:
C:UsersOwnerAnaconda3envs ensorflowTest1python.exe C:/Users/Owner/PycharmProjects/tensorflowTest1/main.py
1.12.0
Training set: (404, 13)
Testing set: (102, 13)
[32. 27.5 32. 23.1 50. 20.6 22.6 36.2 21.8 19.5]
[-0.39725269 1.41205707 -1.12664623 -0.25683275 -1.027385 0.72635358
-1.00016413 0.02383449 -0.51114231 -0.04753316 -1.49067405 0.41584124
-0.83648691]
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 64) 896
_________________________________________________________________
dense_1 (Dense) (None, 64) 4160
_________________________________________________________________
dense_2 (Dense) (None, 1) 65
=================================================================
Total params: 5,121
Trainable params: 5,121
Non-trainable params: 0
_________________________________________________________________
2018-12-02 14:58:27.908127: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX
....................................................................................................
....................................................................................................
....................................................................................................
....................................................................................................
....................................................................................................Testing set Mean Abs Error: $2717.02
Process finished with exit code 0
答案
我已经回答了我自己的问题!
事实证明,我必须使用plt.show()
在不同的窗口上实际生成相应的可视化。新窗口将描述plt
对象的最新初始化和声明值。
不过,谢谢你的帮助!
以上是关于可视化不出现在Tensorflow-PyCharm IDE中的主要内容,如果未能解决你的问题,请参考以下文章