Files
machine_learning_projects/3.宝可梦数据集分析/小组作业/web.py
T
less IS more 966c040379 小组作业
Signed-off-by: less IS more <13190735+wnflt@user.noreply.gitee.com>
2023-07-17 01:51:52 +00:00

76 lines
2.7 KiB
Python

from flask import Flask, render_template, request
import tensorflow as tf
import cv2
import numpy as np
import os
import pandas as pd
app = Flask(__name__)
root_dir = "images/images"
# 获取图片数据
files = os.path.join(root_dir)
File_names = os.listdir(files)
# 属性数据集
data = pd.read_csv("pokemon.csv")
data_dict = {}
for key, val in zip(data["Name"], data["Type1"]): # 将多个可迭代对象按照索引位进行排序
data_dict[key] = val
labels = data["Type1"].unique()
labels_idx = dict(zip(labels, range(len(labels))))
# 数据预处理
final_images = []
final_labels = []
for file in File_names:
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(len(final_labels), 1)
model = tf.keras.Sequential([ # 用于构造序列模型
tf.keras.layers.Flatten(input_shape=(120, 120, 3)),
tf.keras.layers.Dense(100, activation='relu'),
tf.keras.layers.Dense(100, activation='relu'),
tf.keras.layers.Dense(100, activation='relu'),
tf.keras.layers.Dense(len(labels))
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(final_images, final_labels, epochs=20)
# 自定义 enumerate 函数
def custom_enumerate(iterable, start=0): # 用于在迭代过程中同时获得索引和值
return zip(range(start, len(iterable) + start), iterable)
# 注册自定义 enumerate 函数
app.jinja_env.globals['enumerate'] = custom_enumerate
@app.route('/')
def home():
random_indices = np.random.choice(len(final_images), 10, replace=False)
random_images = [File_names[i] for i in random_indices]
random_labels = [final_labels[i] for i in random_indices]
return render_template('index.html', images=random_images, labels=random_labels) # 渲染名为'index.html'的模板,并将‘random_images’和'random_labels'作为参数传递给index
@app.route('/predict', methods=['POST'])
def predict():
index = int(request.form['index']) # 从post请求的表单数据中获得名为'index'的字段
image = final_images[index]
prediction = model.predict(np.array([image]))
predicted_label = np.argmax(prediction)
predicted_attribute = labels[predicted_label]
return render_template('result.html', prediction=predicted_attribute)
if __name__ == '__main__':
app.run(debug=True)