簡體   English   中英

ValueError:目標結構的類型為`<class 'nonetype'> ` 無 但是輸入結構是一個序列 (<class 'list'> ) 長度為 0</class></class>

[英]ValueError: The target structure is of type `<class 'NoneType'>` None However the input structure is a sequence (<class 'list'>) of length 0

我正在嘗試使用樹莓派 4 中的加速度計數據部署分類 model 用於秋季和不秋季。但是,在重塑它們時,tensorflow 或 numpy 似乎有問題。 我得到的確切錯誤是ValueError: The target structure is of type <class 'NoneType'> None 但是輸入結構是長度為 0 的序列 (<class 'list'>)。 [] nest 不能保證它是安全的到 map 一個到另一個。

部署代碼可以在這里找到。

import numpy as np
import pandas as pd
from tensorflow.keras.models import load_model


import board
import scipy.stats as stats
import adafruit_mpu6050
from math import atan2,degrees,pow
import warnings
warnings.filterwarnings("ignore")

import pandas as pd
import numpy as np

print("Inititating")

model_trained = load_model('model_cnn.h5')
print('\n',model_trained.summary())

i2c = board.I2C()
mpu = adafruit_mpu6050.MPU6050(i2c)
mpu_accelerometer_range = adafruit_mpu6050.Range.RANGE_4_G

data1 = []
i = 0
while(i<2000):
    
    
    i+=1
    ax,ay,az = mpu.acceleration
    
    data1.append([ax,ay,az])
    df = pd.DataFrame(data1)
    #print('length of df',len(df))
    columns = ['x','y','z']
    df.columns = columns
    #print(df)
    Fs = 50
    frame_size = Fs*4
    hop_size = Fs*2
    
    frames = []
    N_FEATURES = 3
    
    for i in range(0,len(df)-frame_size,hop_size):
        x = df['x'].values[i:i+frame_size]
        y = df['y'].values[i:i+frame_size]
        z = df['z'].values[i:i+frame_size]
        
        frames.append([x,y,z])
        
    #print('leeeee',len(frames))
    
    # converting frames to numpy array
    frames = np.asarray(frames).reshape(-1,frame_size,N_FEATURES)
    #print('frames',len(frames))

    k = int((len(df)-frame_size)/hop_size)+1
    print('type is',type(k))
    
    
    X_test = frames.reshape(k,200,3,1)
    y_pred = model_trained.predict_classes(X_test)
    print(y_pred) 

        

我在具有 3 列 x 軸加速度、y 軸加速度、z 軸加速度的 cnn 數據上使用跳躍 window 方法。 當我在while循環之外運行以下代碼時, model 給出 output 但不能實時使用。

X_test = frames.reshape(k,200,3,1)
y_pred = model_trained.predict_classes(X_test)
print(y_pred) 

培訓代碼

# Importing

import numpy as np
import pandas as pd
#import seaborn as sns
import tensorflow as tf
#import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Flatten, Dense, Dropout, BatchNormalization,MaxPooling2D
from tensorflow.keras.layers import Conv2D,MaxPool2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import load_model


physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
    tf.config.experimental.set_memory_growth(physical_devices[0], True)

import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2"


df = pd.read_csv('fall_nofall_10_with_labels.csv')



df.columns = ['a','activity','time','realtime','x','y','z','gyro-x','gyro-y','gyro-z']





data = df.drop(['a','realtime','gyro-x','gyro-y','gyro-z'],axis=1)


print(data['activity'].value_counts())




# # sampling rate


Fs = 50



activities = data['activity'].value_counts().index






balanced_data = data.drop(['time'], axis = 1).copy()






balanced_data['activity'].value_counts()



from sklearn.preprocessing import LabelEncoder
label = LabelEncoder()
balanced_data['label'] = label.fit_transform(df['activity'])



### Frame Prepration
import scipy.stats as stats
Fs = 50
frame_size = Fs*4 #(4 seconds)
# 200x200x3 will be feeded in
hop_size = Fs*2 #(How much overlap) make advancement with 100 data samples



def get_frames(df,frame_size,hop_size):
    N_FEATURES = 3 # input feature is x,y and z
    frames = []
    labels = []

    for i in range(0,len(df) - frame_size,hop_size):
        x = df['x'].values[i:i+frame_size] # 0 to 4 second then 1 to 5 seconds
        y = df['y'].values[i:i+frame_size]
        z = df['z'].values[i:i+frame_size]

        # activity which comes most number of time we'll be considering that
        label = stats.mode(df['label'][i:i+frame_size])[0][0]
        # labels = label[0][0]

        frames.append([x,y,z])
        labels.append(label)

    # convert into numpy array
    frames = np.asarray(frames).reshape(-1,frame_size,N_FEATURES)
    labels = np.asarray(labels)

    return frames,labels



X,y = get_frames(balanced_data,frame_size,hop_size)



print(X.shape,y.shape)




X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0, stratify = y)
X_train.shape, X_test.shape




X_train[0].shape, X_test[0].shape



X_train = X_train.reshape(39,200,3,1)
X_test = X_test.reshape(10,200,3,1)



X_train[0].shape,X_test[0].shape


# ## Creating CNN model



model = Sequential()
model.add(Conv2D(16,(2,2),activation='relu',input_shape=X_train[0].shape))
# model.add(MaxPooling2D(pool_size=(1,1)))
model.add(Dropout(0.1))


model.add(Conv2D(64,(2,2),activation='relu'))
# model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))

model.add(Flatten())

model.add(Dense(64,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2,activation='sigmoid'))





model.summary()



model.compile(optimizer=Adam(learning_rate = 0.001), loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
history = model.fit(X_train, y_train, epochs = 10, validation_data= (X_test, y_test), verbose=1)

model.save("model_cnn.h5")




# load the model
model_trained = load_model('model_cnn.h5')
# summary of the model
print('\n',model_trained.summary())




from sklearn.metrics import confusion_matrix,classification_report
y_pred = model_trained.predict_classes(X_test)



print(y_pred)



print(classification_report(y_pred,y_test))




print(confusion_matrix(y_pred,y_test))

完整的追溯:

Traceback (most recent call last):
  File "cnn_nofall_live.py", line 68, in <module>
    y_pred = model_trained.predict_classes(X_test)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/sequential.py", line 338, in predict_classes
    proba = self.predict(x, batch_size=batch_size, verbose=verbose)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/training.py", line 1013, in predict
    use_multiprocessing=use_multiprocessing)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/training_v2.py", line 498, in predict
    workers=workers, use_multiprocessing=use_multiprocessing, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/training_v2.py", line 475, in _model_iteration
    total_epochs=1)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/training_v2.py", line 187, in run_one_epoch
    aggregator.finalize()
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/training_utils.py", line 353, in finalize
    self.results = nest.pack_sequence_as(self._structure, self.results)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/util/nest.py", line 504, in pack_sequence_as
    return _pack_sequence_as(structure, flat_sequence, expand_composites)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/util/nest.py", line 453, in _pack_sequence_as
    len(flat_sequence), truncate(flat_sequence, 100)))
ValueError: The target structure is of type `<class 'NoneType'>`
  None
However the input structure is a sequence (<class 'list'>) of length 0.
  []
nest cannot guarantee that it is safe to map one to the other.

我認為您需要發布完整的回溯。 沒有看到就很難調試/幫助

但是 OOTH 一個可能的問題是您在 while 循環for 循環中使用了“i”。 也許將 for 循環索引更改為“j”或其他內容。

嘗試運行此代碼片段以了解我的意思

i=0
while(i<10):
   i+=1
   for i in range(100):
      print(f"for loop i is {i}")
   print(f"while loop i is {i}")

順便說一句,你為此努力嗎?

data1 = []
i = 0
while(i<2000):
    i+=1
    ax,ay,az = mpu.acceleration
    data1.append([ax,ay,az])
    df = pd.DataFrame(data1, columns=['x','y','z'])
    frame_size = 200
    hop_size = 100
    
frames = []
N_FEATURES = 3
    
for i in range(0,len(df)-frame_size,hop_size):
    x = df['x'].values[i:i+frame_size]
    y = df['y'].values[i:i+frame_size]
    z = df['z'].values[i:i+frame_size]
    
    frames.append([x,y,z])

frames = np.array(frames)

k = int((len(df)-frame_size)/hop_size)

X_test = frames.reshape(k,200,3,1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM