tf2
Posted cyd1310997
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了tf2相关的知识,希望对你有一定的参考价值。
np.linspace np.random.randn
#ipython qtconsole --pylab=inline
import numpy as np
import matplotlib.pyplot as plt
import tensorflow.keras as kr
x = np.linspace(1,100,30)
y = x*3+7+np.random.randn(30)*6
model = kr.Sequential()
model.add(kr.layers.Dense(1, input_shape=(1,)))
model.summary()
model.compile(optimizer='adam', loss='mse')
history = model.fit(x, y, epochs=5000)
prediction = model.predict(x)
plt.scatter(x,y)
plt.scatter(x,prediction)
plt.scatter(x,x*3+7)
(plt.scatter(x,prediction),plt.scatter(x,y))
(plt.scatter(x,x*3+7), plt.scatter(x,prediction))
tf.keras.datasets.mnist
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test, verbose=2)
prediction = model.predict(x_test)
for i in range(5):
plt.ylabel('No.' + str(i))
plt.xlabel('actual: ' + str(y_test[i]))
plt.title('prediction: ' + str(np.argmax(prediction[i])))
plt.imshow(x_test[i])
plt.show()
tf.keras.datasets.fashion_mnist
import tensorflow.keras as kr
import matplotlib.pyplot as plt
import numpy as np
data = kr.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = data.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images = train_images/255.0
test_images = test_images/255.0
model = kr.Sequential([
kr.layers.Flatten(input_shape=(28,28)),
kr.layers.Dense(128, activation='relu'),
kr.layers.Dense(10, activation='softmax')])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
test_loss, test_acc = model.evaluate(test_images, test_labels)
prediction = model.predict(test_images)
for i in range(5):
plt.ylabel('No.' + str(i))
plt.xlabel('Actual: ' + class_names[test_labels[i]])
plt.title('prediction: ' + class_names[np.argmax(prediction[i])])
plt.imshow(test_images[i])
plt.show()
以上是关于tf2的主要内容,如果未能解决你的问题,请参考以下文章
使用 cx_Freeze 时出现问题:“无法导入名称 'tf2'”
使用 TF2.0 训练 RNN 的每次迭代逐渐增加内存使用量