gpt4 book ai didi

python - 可视化未出现在 Tensorflow-PyCharm IDE 中

转载 作者:行者123 更新时间:2023-12-01 01:23:15 28 4
gpt4 key购买 nike

我正在使用 PyCharm 社区版和 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:\Users\Owner\Anaconda3\envs\tensorflowTest1\python.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 对象的最新初始化和声明值。

不过还是谢谢你的帮助!

关于python - 可视化未出现在 Tensorflow-PyCharm IDE 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53585054/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com