python - TensorFlow 将所有图像分类为同一类
问题描述
问题
我在 TensorFlow 中创建了一个图像分类器 CNN,用于将图形分类为以下三个类之一:线性、二次或三次。我遵循了https://www.tensorflow.org/tutorials/images/classification上的文档。我已经对代码的所有前面部分进行了单元测试,它们工作得非常好。但是在对图的图像进行标记时,每个图都被归类为与任何图像This image most likely belongs to Cubic Sinusoidal with a 88.71 percent confidence.
完全相同的分类和概率。
尝试修复
我已经将我的代码与文档进行了比较,似乎没有任何问题。如果有人可以提供帮助,那就太好了。我什至在这里找到了类似的问答。
代码
我的代码如下。Colab 笔记本在这里。我已经包含了我的所有代码,因为我不确定问题是什么:
pip install tensorflow
pip install numpy
pip install matplotlib
!git clone https://github.com/Refath/SinusoidalAnalyzer.git
# Import Libraries
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout
from tensorflow.keras import layers
from tensorflow.keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
# Load the Data
from keras.datasets import cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
import pathlib
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file(origin = dataset_url,
fname = "flower_photos",
untar = True)
data_dir = pathlib.Path(data_dir)
import pathlib
dataset_url = "https://barisciencelab.tech/Graphs.tar.gz"
data_dir = tf.keras.utils.get_file(origin = dataset_url,
fname = "FunctionIdentifier",
untar = True)
data_dir = pathlib.Path(data_dir)
print(list(data_dir.glob('*/*.png')))
image_count = len(list(data_dir.glob('*/*.png')))
print(image_count)
import numpy as np
import os
import PIL
import PIL.Image
import tensorflow as tf
import tensorflow_datasets as tfds
graphs = list(data_dir.glob('*/*.png'))
print(graphs)
PIL.Image.open(str(graphs[6]))
batch_size = 32
img_height = 36
img_width = 36
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
class_names = ['Cubic Sinusoidal', 'Linear Sinusoidal', 'Quadratic Sinusoidal']
print(class_names)
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
normalization_layer = tf.keras.layers.experimental.preprocessing.Rescaling(1./255)
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(normalized_ds))
first_image = image_batch[0]
# Notice the pixels values are now in `[0,1]`.
print(np.min(first_image), np.max(first_image))
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
num_classes = 3
model = tf.keras.Sequential([
tf.keras.layers.experimental.preprocessing.Rescaling(1./255),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(num_classes)
])
model.compile(
optimizer='adam',
loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.summary()
epochs = 3
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=3
)
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
"""# 1-Sample *Cubic* Test (Passed; Accuracy: 99.91%)"""
cubic_url = "https://raw.githubusercontent.com/Refath/SinusoidalAnalyzer/main/CubicSinusoidal_1.png"
cubic_path = tf.keras.utils.get_file('CubicSinusoidal_1', origin=cubic_url)
img = keras.preprocessing.image.load_img(
cubic_path, target_size=(img_height, img_width)
)
img_array = keras.preprocessing.image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create a batch
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print(
"This image most likely belongs to {} with a {:.2f} percent confidence."
.format(class_names[np.argmax(score)], 100 * np.max(score))
)
"""# 1-Sample *Quadratic* Test (Failed :( )"""
quad_url = "https://raw.githubusercontent.com/Refath/SinusoidalAnalyzer/main/QuadSinusoidal_1.png"
quad_path = tf.keras.utils.get_file('QuadSinusoidal_1', origin=quad_url)
img = keras.preprocessing.image.load_img(
quad_path, target_size=(img_height, img_width)
)
img_array = keras.preprocessing.image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create a batch
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print(
"This image most likely belongs to {} with a {:.2f} percent confidence."
.format(class_names[np.argmax(score)], 100 * np.max(score))
)
lin_url = "https://raw.githubusercontent.com/Refath/SinusoidalAnalyzer/main/LinSinusoidal_1.png"
lin_path = tf.keras.utils.get_file('QuadSinusoidal_1', origin=lin_url)
img = keras.preprocessing.image.load_img(
lin_path, target_size=(img_height, img_width)
)
img_array = keras.preprocessing.image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create a batch
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print(
"This image most likely belongs to {} with a {:.2f} percent confidence."
.format(class_names[np.argmax(score)], 100 * np.max(score))
)
解决方案
推荐阅读
- python - Python3:如何将 Excel 电子表格导入 python 项目?(我使用 repl.it 网站学习 python3)
- c# - 在 WPF 组合框中键入时移动选定的索引
- outlook-addin - Outlook WebAddin 被检测为上下文插件而不是功能区插件
- gcc - 使用 GCC 对模块内的 fortran 子例程进行外部命名
- matlab - 从 HDL 到软件的 CRC-32 算法
- sql - 有没有办法停止更新,同时在 postgresql 中保留更新的行?
- android - 使用旧的 buildToolsVersion 23.0.3 反应原生 init 项目
- angular - 在 Angular http Post 请求中获得完整响应
- javascript - 将 jest.fn() 函数传递给酶浅渲染中的 mapDispatchToProps
- javascript - ASP.Net核心,选中复选框时如何记录用户信息?