#python #image #conv-neural-network #regression #prediction
#питон #изображение #conv-нейронная сеть #регрессия #предсказание
Вопрос:
import numpy as np import pandas as pd from pathlib import Path import os.path from sklearn.model_selection import train_test_split import tensorflow as tf from sklearn.metrics import r2_score from keras.applications.efficientnet import EfficientNetB3 import gc from keras.models import Sequential from keras import layers, models from keras import Input from keras.models import Model from keras.preprocessing.image import ImageDataGenerator from keras import optimizers, initializers, regularizers, metrics from keras.callbacks import ModelCheckpoint import os from glob import glob from PIL import Image import matplotlib.pyplot as plt import numpy as np from tensorflow.keras import optimizers from keras.layers import Conv2D,MaxPool2D,GlobalAveragePooling2D,AveragePooling2D from keras.layers import Dense,Dropout,Activation,Flatten import sys # Repository source: https://github.com/qubvel/efficientnet sys.path.append(os.path.abspath('../input/efficientnet/efficientnet-master/efficientnet-master/')) from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau image_dir = Path('/content/drive/MyDrive/processed') filepaths = pd.Series(list(image_dir.glob(r'**/*.jpg')), name='Filepath').astype(str) TS = pd.Series(sorted([int(l.split('TS_')[1].split('/pre')[0]) for l in filepaths]),name='TS').astype(np.int) images = pd.concat([filepaths, TS], axis=1).sample(frac=1.0, random_state=1).reset_index(drop=True) image_df = images.sample(2020, random_state=1).reset_index(drop=True) train_df, test_df = train_test_split(image_df, train_size=0.7, shuffle=True, random_state=1) train_generator = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1./255, validation_split=0.2 ) test_generator = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1./255 ) train_input = train_generator.flow_from_dataframe( dataframe=train_df, x_col='Filepath', y_col='TS', target_size=(256, 256), color_mode='grayscale', class_mode='raw', batch_size=1, shuffle=True, seed=42, subset='training' ) val_input = train_generator.flow_from_dataframe( dataframe=train_df, x_col='Filepath', y_col='TS', target_size=(256, 256), color_mode='grayscale', class_mode='raw', batch_size=1, shuffle=True, seed=42, subset='validation' ) test_input = test_generator.flow_from_dataframe( dataframe=test_df, x_col='Filepath', y_col='TS', target_size=(256, 256), color_mode='grayscale', class_mode='raw', batch_size=1, shuffle=False ) inputs = tf.keras.Input(shape=(256, 256, 1)) x = tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu')(inputs) x = tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu')(x) x = tf.keras.layers.MaxPool2D()(x) x = tf.keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu')(x) x = tf.keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu')(x) x = tf.keras.layers.MaxPool2D()(x) x = tf.keras.layers.Conv2D(filters=128, kernel_size=(3, 3), activation='relu')(x) x = tf.keras.layers.Conv2D(filters=128, kernel_size=(3, 3), activation='relu')(x) x = tf.keras.layers.MaxPool2D()(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dense(128, kernel_initializer='he_normal')(x) x = tf.keras.layers.Dense(64, kernel_initializer='he_normal')(x) outputs = tf.keras.layers.Dense(1, activation='linear')(x) model = tf.keras.Model(inputs=inputs, outputs=outputs) model.compile( optimizer='adam', loss='mae' ) history = model.fit( train_input, validation_data=val_input, epochs=10, callbacks=[ tf.keras.callbacks.EarlyStopping( monitor='val_loss', patience=5, restore_best_weights=True ) ] ) #Results predicted_TS = np.squeeze(model.predict(test_input)) true_TS = test_input.labels rmse = np.sqrt(model.evaluate(test_input, verbose=0)) print(" Test RMSE: {:.5f}".format(rmse)) r2 = r2_score(true_TS, predicted_TS) print("Test R^2 Score: {:.5f}".format(r2)) null_rmse = np.sqrt(np.sum((true_TS - np.mean(true_TS))**2) / len(true_TS)) print("Null/Baseline Model Test RMSE: {:.5f}".format(null_rmse))
Изображение — это микроструктура сплава, а TS-прочность сплава на растяжение. Я подумал, что если я помещу изображения в эту модель, это сможет предсказать рассеянные значения прогноза.
Я не могу понять, почему результат прогнозирования имеет почти одинаковые значения.
И как я могу уменьшить RMSE?
Это приводит к ужасному RMSE