tensorflow2笔记

常量:

import tensorflow as tf

print(tf.__version__)

x=tf.constant(0.)
y=tf.constant(1.)
for iteration in range(50):
    x=x+y
    y=y/2
print(x.numpy())
2.0.0
2.0

搭建神经网络

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from tensorflow import keras

# 导入数据
FM_data = keras.datasets.fashion_mnist
(x_train_all, y_train_all), (x_test, y_test) = FM_data.load_data()
x_cv, x_train = x_train_all[:5000], x_train_all[5000:]
y_cv, y_train = y_train_all[:5000], y_train_all[5000:]

# 归一化
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
x_train_scaled = scaler.fit_transform(
    x_train.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)
x_cv_scaled = scaler.transform(
    x_cv.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)
x_test_scaled = scaler.transform(
    x_test.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)

print(x_train.shape)
print(y_train.shape)
print(x_cv.shape)
print(y_cv.shape)
print(x_test.shape)
print(y_test.shape)

# 展示一些图片
def show_imgs(n_rows, n_cols, x_data, y_data, class_names):
    plt.figure(figsize=(n_cols * 1.4, n_rows * 1.6))
    for row in range(n_rows):
        for col in range(n_cols):
            index = n_cols * row + col
            plt.subplot(n_rows, n_cols, index + 1)
            plt.imshow(x_data[index], cmap="binary",
                       interpolation='nearest')  # 缩放图片时的方法
            plt.axis('off')
            plt.title(class_names[y_data[index]])
    plt.show()
class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal',
               'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
show_imgs(5, 8, x_train, y_train, class_names)

# 展示学习曲线
def show_learning_curves(history):
    pd.DataFrame(history.history).plot(figsize=(8, 5))
    plt.grid(True)
    plt.gca().set_ylim(0, 1)
    plt.show()

# 模型创建与训练
def getMode():
    toTrain=True
    if os.path.exists('my_model.h5'):
        model= tf.keras.models.load_model('my_model.h5')
    else:
        model = keras.models.Sequential([
            keras.layers.Flatten(input_shape=[28, 28]),
            keras.layers.Dense(64, activation='relu'),
            keras.layers.Dropout(0.2),
            keras.layers.Dense(64, activation='relu'),
            keras.layers.Dropout(0.2),
            keras.layers.Dense(10, activation='softmax')
        ])
        # 非onehot编码时使用sparse_categorical_crossentropy,onehot时使用categorical_crossentropy
        model.compile(loss='categorical_crossentropy',
                      optimizer='adam',
                      metrics=['accuracy'])
    print(tf.keras.utils.to_categorical(y_train))

    if toTrain:
        history = model.fit(x_train_scaled, tf.keras.utils.to_categorical(y_train), epochs=30,
                            validation_data=(x_cv_scaled, tf.keras.utils.to_categorical(y_cv)))
        show_learning_curves(history)
    # 保存模型与训练好的参数
    model.save('my_model.h5')
    return model

# 进行预测
model=getMode()
loss,acc=model.evaluate(x_test_scaled, tf.keras.utils.to_categorical(y_test))
print("model loss:{:.2}, acc:{:.2%}".format(loss,acc))
model loss:0.4, acc:88.22%
发布了723 篇原创文章 · 获赞 314 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/jk_chen_acmer/article/details/103671725