966c040379
Signed-off-by: less IS more <13190735+wnflt@user.noreply.gitee.com>
77 lines
2.8 KiB
Python
77 lines
2.8 KiB
Python
import os
|
|
import cv2
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
|
|
root_dir = "images/images"
|
|
|
|
# 获取图片数据
|
|
files = os.path.join(root_dir)
|
|
File_names = os.listdir(files)
|
|
print(File_names) # 所有图片名称
|
|
|
|
|
|
# 属性数据集
|
|
data = pd.read_csv("pokemon.csv")
|
|
print(data.head())
|
|
|
|
# 获得名字与第一属性的对应关系
|
|
data_dict = {}
|
|
for key, val in zip(data["Name"], data["Type1"]):
|
|
data_dict[key] = val
|
|
print(data_dict)
|
|
|
|
# 获取属性集合
|
|
labels = data["Type1"].unique()
|
|
print(labels)
|
|
|
|
# 给属性以序号
|
|
ids = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
|
|
labels_idx = dict(zip(labels, ids))
|
|
print(labels_idx)
|
|
|
|
# 数据预处理
|
|
final_images = []
|
|
final_labels = [] # 初始化空列表用于储存图像和标签
|
|
count = 0
|
|
files = os.path.join(root_dir) # 将根目录路径与文件名相结合,获得所有的图片
|
|
for file in File_names:
|
|
count += 1
|
|
img = cv2.imread(os.path.join(root_dir, file), cv2.COLOR_BGR2GRAY) # 读取图像文件并转为一个表示图像的多维数组
|
|
label = labels_idx[data_dict[file.split(".")[0]]] # 构建文件与标签的映射关系
|
|
final_images.append(np.array(img))
|
|
final_labels.append(np.array(label))
|
|
|
|
# 对储存数据进行类型和形状的调整
|
|
final_images = np.array(final_images, dtype=np.float32) / 255.0 # 储存图片数据(像素值)
|
|
final_labels = np.array(final_labels, dtype=np.int8).reshape(809, 1)
|
|
|
|
|
|
import tensorflow as tf
|
|
|
|
|
|
# 创建顺序模型model
|
|
model = tf.keras.Sequential([
|
|
tf.keras.layers.Flatten(input_shape=(120, 120, 3)), # 将输入数据转化为一维向量
|
|
tf.keras.layers.Dense(100, activation='relu'), # 创建有100个神经元的全连接层,并选取ReLu函数为激活函数
|
|
tf.keras.layers.Dense(100, activation='relu'),
|
|
tf.keras.layers.Dense(100, activation='relu'),
|
|
tf.keras.layers.Dense(18)
|
|
])
|
|
print(model.summary()) # 获得模型信息
|
|
|
|
# 配置模型的训练参数
|
|
model.compile(optimizer='adam',
|
|
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), # 稀疏分类交叉损失函数
|
|
metrics=['accuracy']) # 评估指标为准确率
|
|
history = model.fit(final_images, final_labels, epochs=20) # 对模型进行训练
|
|
probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()]) # 建立新的模型,新增一个Softmax层,用于生成每个结果的概率
|
|
predictions = probability_model.predict(final_images)
|
|
|
|
print("\n", predictions[1])
|
|
id = np.argmax(predictions[1]) # id表示所属的某个属性(type1)
|
|
print("\n通过模型预测的id为: {}"
|
|
"\n对应这个id的宝可梦属性为: {} ".format(id, labels[id]))
|
|
print("模型准确率为:", history.history['accuracy'][-1])
|