需要源码和数据集请点赞关注收藏后评论区留言私信~~~
一、半环形数据分类
Tensorflow是常见流行的深度学习平台,下面利用它来对半环形数据集进行分类
首先产生半环形数据集
接着开始训练模型 总共训练三十次 可以看到损失在逐渐降低,精确度在逐渐提高
结果展示如下, 可以看出大致可以拟合出一条折线将数据集分为两个区域 类似于kmeans算法
部分代码如下
# encoding: utf-8 import numpy as np from sklearn.datasets import make_moons import tensorflow as tf from sklearn.model_selection import train_test_split from tensorflow.keras import layers, Sequential, optimizers, losses, metrics from tensorflow.keras.layers import Dense import matplotlib.pyplot as plt # 产生一个半环形数据集 X, y = make_moons(200, noise=0.25, random_state=100) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=2) print(X.shape, y.shape) def make_plot(X, y, plot_name, XX=None, YY=None, preds=None): plt.figure() axes = plt.gca() x_min = X[:, 0].min() - 1 x_max = X[:, 0].max() + 1 y_min = X[:, 1].min() - 1 y_max = X[:, 1].max() + 1 axes.set_xlim([x_min, x_max]) axes.set_ylim([y_min, y_max]) axes.set(xlabel="$x_l$", ylabel="$x_2$") if XX is None and YY is None and preds is None: yr = y.ravel() for step in range(X[:, 0].size): if yr[step] == 1: plt.scatter(X[step, 0], X[step, 1], c='b', s=20, edgecolors='none', marker='x') else: plt.scatter(X[step, 0], X[step, 1], c='r', s=30, edgecolors='none', marker='o') plt.show() else: plt.contour(XX, YY, preds, cmap=plt.cm.spring, alpha=0.8) plt.scatter(X[:, 0], X[:, 1], c=y, s=20, cmap=plt.cm.Greens, edgecolors='k') plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.title(plot_name) plt.show() make_plot(X, y, None) #创建容器 model = Sequential() #创建第一层 model.add(Dense(8, input_dim=2, activation='relu')) for _ in range(3): model.add(Dense(32, activation='relu')) #创建最后一层,激活 model y_min = X[:, 1].min() - 1 y_max = X[:, 1].max() + 1 XX, YY = np.meshgrid(np.arange(x_min, x_max, 0.01), np.arange(y_min, y_max, 0.01)) Z = model.predict_classes(np.c_[XX.ravel(), YY.ravel()]) preds = Z.reshape(XX.shape) title = "分类结果" make_plot(X_train, y_train, title, XX, YY, preds)
二、手写数字识别
下面使用深度学习进行一个简单的手写数字识别
输出结果如下 精度大概在百分之九十七
代码如下
import tensorflow as tf #载入MNIST 数据集。 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 #使用tf.keras.Sequential将模型的各层堆叠,并设置参数 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)
三、猫狗识别
下面利用tensorflow平台实现对猫狗品种的识别
原图片如下
识别结果如下 第二项是品种 第三项是预测的概率
部分代码如下
from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions import numpy as np from PIL import ImageFont, ImageDraw, Image import cv2 img_path = 'dog.jpg' #进行狗的判断 #img_path = 'cat.jpg' #进行猫的判断 #img_path = 'deer.jpg' #进行鹿的判断 img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) weights_path = 'resnet50_weights_tf_dim_ordering_tf_kernels.h5' def get_model(): model = ResNet50(weights=weights_path) # 导入模型以及预训练权重 print(model.summary()) # 打印模型概况 return model model = get_model()
创作不易 觉得有帮助请点赞关注收藏~~~