TensorFlow-mnist实际操练(矩阵运算)

TensorFlow-mnist实际操练(矩阵运算,非卷积运算

硬件:NVIDIA-GTX1080

软件:Windows7、python3.6.5、tensorflow-gpu-1.4.0

一、基础知识

1、matmul's different from tf.nn.conv2d

2、None*784  x 784*10 = None*10

二、数据下载

下载链接

三、代码展示

import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data

def add_layer(inputs, in_size, out_size, activate_function = None):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    Biases = tf.Variable(tf.zeros([1,out_size]) + 0.1)

    #matmul's different from tf.nn.conv2d
    Wx_plus_b = tf.matmul(inputs, Weights) + Biases #None*784  x 784*10 = None*10
    
    if activate_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activate_function(Wx_plus_b)

    return outputs

def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict = {xs: v_xs})
    correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))#ture to 1.0, false to 0.0
    result = sess.run(accuracy)
    return result

mnist = input_data.read_data_sets('MNIST_data/', one_hot = True)

xs = tf.placeholder(tf.float32, [None, 784])
ys = tf.placeholder(tf.float32, [None, 10])

prediction = add_layer(xs, 784, 10, activate_function = tf.nn.softmax)

cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices = [1]))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train_step = optimizer.minimize(cross_entropy)

init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict = {xs: batch_xs, ys: batch_ys})
    if i%50 == 0:
        print(compute_accuracy(mnist.test.images, mnist.test.labels))

sess.close()

四、结果展示

Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
0.1004
0.6287
0.7282
0.7737
0.7929
0.8175
0.8315
0.8372
0.8456
0.8529
0.8572
0.8594
0.8607
0.8677
0.8613
0.8678
0.8731
0.8748
0.8752
0.8777

 

任何问题请加唯一QQ2258205918(名称samylee)!

唯一VX:samylee_csdn

以下是使用TensorFlow - Keras函数式API实现Fashion - MNIST数据集训练的详细步骤及代码示例: ### 1. 导入必要的库 ```python import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt ``` ### 2. 导入Fashion - MNIST数据集 ```python fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() class_names = ['T - shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] ``` ### 3. 数据预处理 将图像数据归一化到0到1的范围,因为神经网络通常在归一化的数据上表现更好。 ```python train_images = train_images / 255.0 test_images = test_images / 255.0 ``` ### 4. 使用函数式API构建模型 ```python # 定义输入层 inputs = keras.Input(shape=(28, 28)) # 将2D图像数据展平为1D向量 x = keras.layers.Flatten()(inputs) # 第一个全连接层 x = keras.layers.Dense(128, activation='relu')(x) # 输出层,使用softmax激活函数进行多分类 outputs = keras.layers.Dense(10, activation='softmax')(x) # 创建模型 model = keras.Model(inputs=inputs, outputs=outputs) ``` ### 5. 编译模型 指定优化器、损失函数和评估指标。 ```python model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) ``` ### 6. 训练模型 使用训练数据对模型进行训练。 ```python model.fit(train_images, train_labels, epochs=5) ``` ### 7. 评估模型 使用测试数据评估模型的性能。 ```python test_loss, test_acc = model.evaluate(test_images, test_labels) print(f'Test accuracy: {test_acc}') ``` ### 8. 进行预测 使用训练好的模型对测试数据进行预测。 ```python predictions = model.predict(test_images) print(predictions[0]) # 打印第一个样本的预测结果 print(test_labels[0]) # 打印第一个样本的真实标签 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值