使用tensorflow对Mnist数据集进行字体识别



上代码:

#!/usr/bin/env python
#coding:utf-8

import tensorflow
import pandas as pd
import skflow

train = pd.read_csv('~/Mnist/train.csv')
X_train = train.drop('label',1)
y_train = train['label']

classifier = skflow.TensorFlowLinearClassifier(n_classes=10,batch_size=100,steps=1000,learning_rate=0.01)
classifier.fit(X_train,y_train)
linear_y_predict = classifier.predict(X_test)

#save results for submission onto Kaggle
linear_submission = pd.DataFrame({'ImageId':range(1,28001),'label':linear_y_predict})
linear_submission.to_csv('~/Mnist/linear_submission.csv',index=False)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是基于Python实现LeNet5的MNIST手写字体识别的步骤: 1. 数据准备:下载MNIST数据集,包括训练集和测试集。可以使用Python库`tensorflow_datasets`来下载和加载MNIST数据集。 ```python import tensorflow_datasets as tfds # 加载MNIST数据集 mnist_dataset = tfds.load(name="mnist", split=tfds.Split.TRAIN) mnist_test_dataset = tfds.load(name="mnist", split=tfds.Split.TEST) ``` 2. 数据预处理:对数据进行标准化处理,并将训练集和测试集转换为合适的格式。 ```python def preprocess_data(data): # 将数据转换为浮点数类型 data['image'] = tf.cast(data['image'], tf.float32) # 标准化处理 data['image'] = tf.divide(data['image'], 255.0) # 调整形状 data['image'] = tf.reshape(data['image'], [-1, 28, 28, 1]) # 将标签转换为One-hot编码 data['label'] = tf.one_hot(data['label'], depth=10) return data # 对训练集和测试进行预处理 mnist_dataset = mnist_dataset.map(preprocess_data) mnist_test_dataset = mnist_test_dataset.map(preprocess_data) # 将训练集转换为可迭代的数据集 batch_size = 32 mnist_dataset = mnist_dataset.batch(batch_size) # 将测试集转换为可迭代的数据集 mnist_test_dataset = mnist_test_dataset.batch(batch_size) ``` 3. 构建LeNet5模型:使用TensorFlow构建LeNet5模型,包括卷积层、池化层和全连接层。 ```python from tensorflow.keras import layers, models # 构建LeNet5模型 model = models.Sequential([ layers.Conv2D(filters=6, kernel_size=(5, 5), activation='relu', input_shape=(28, 28, 1)), layers.MaxPooling2D(pool_size=(2, 2)), layers.Conv2D(filters=16, kernel_size=(5, 5), activation='relu'), layers.MaxPooling2D(pool_size=(2, 2)), layers.Flatten(), layers.Dense(units=120, activation='relu'), layers.Dense(units=84, activation='relu'), layers.Dense(units=10, activation='softmax') ]) ``` 4. 编译模型:定义损失函数、优化器和评估指标。 ```python # 定义损失函数、优化器和评估指标 model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ``` 5. 训练模型:使用训练集训练模型,并在测试集上进行评估。 ```python epochs = 10 history = model.fit(mnist_dataset, epochs=epochs, validation_data=mnist_test_dataset) ``` 6. 可视化训练过程:使用Matplotlib库可视化训练过程。 ```python import matplotlib.pyplot as plt # 可视化训练过程 plt.plot(history.history['accuracy'], label='training accuracy') plt.plot(history.history['val_accuracy'], label='validation accuracy') plt.title('Training and Validation Accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend() plt.show() ``` 7. 预测结果:使用训练好的模型对新的手写数字进行预测。 ```python import numpy as np # 加载新的手写数字图片 new_image = plt.imread('new_image.png') # 将图片转换为灰度图像 new_image = np.dot(new_image[...,:3], [0.299, 0.587, 0.114]) # 调整形状 new_image = np.reshape(new_image, (1, 28, 28, 1)) # 标准化处理 new_image = new_image / 255.0 # 对新的手写数字进行预测 prediction = model.predict(new_image) # 打印预测结果 print(np.argmax(prediction)) ``` 以上就是基于Python实现LeNet5的MNIST手写字体识别的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值