【问题标题】:Error with udemy Deep learning code of ANNudemy ANN 的深度学习代码出错
【发布时间】:2020-01-27 17:05:55
【问题描述】:

*我正在参加关于 Udemy 的深度学习课程。我写的代码和老师说的完全一样。但是classifier.fit(X_train, y_train, batch_size = 10,epochs = 100)之后出现问题,错误如下

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values

# Encoding categorical data


from sklearn.preprocessing import OneHotEncoder, LabelEncoder

from sklearn.compose import ColumnTransformer

label_encoder_x_1 = LabelEncoder()
X[: , 2] = label_encoder_x_1.fit_transform(X[:,2])
transformer = ColumnTransformer(
    transformers=[
        ("OneHot",        # Just a name
         OneHotEncoder(), # The transformer class
         [1]              # The column(s) to be applied on.
         )
    ],
    remainder='passthrough' # donot apply anything to the remaining columns
)
X = transformer.fit_transform(X.tolist())
X = X.astype('float64')
X = X[:, 1:]

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

#importing keras 
import keras
from keras.models import Sequential
from keras.layers import Dense
# Fitting classifier to the Training set
# Create your classifier here
classifier = Sequential()
classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', input_dim = 11))
classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu'))
classifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

classifier.fit(X_train, y_train, batch_size = 10, epochs = 100) 
# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

文件“C:\Anaconda3\envs\py37\lib\site-packages\sklearn\metrics_classification.py”,第 268 行,位于混淆矩阵中 y_type, y_true, y_pred = _check_targets(y_true, y_pred)

文件“C:\Anaconda3\envs\py37\lib\site-packages\sklearn\metrics_classification.py”,第 90 行,在 _check_targets "和 {1} 个目标".format(type_true, type_pred))

ValueError:分类指标无法处理二进制和连续目标的混合

如何解决*

【问题讨论】:

    标签: python keras deep-learning


    【解决方案1】:

    问题似乎出在y_pred = classifier.predict(X_test) 这一行上。根据文档predict_classes 用于获取类预测,https://www.tensorflow.org/api_docs/python/tf/keras/Sequential#predict_classes。 Predict 正在返回不是类标签的连续值。我对你的代码做了一些小的调整,

    # Importing the libraries
    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    
    # Importing the dataset
    dataset = pd.read_csv('Churn_Modelling.csv')
    X = dataset.iloc[:, 3:13].values
    y = dataset.iloc[:, 13].values
    
    #print(X)
    #print(y)
    
    
    
    # Encoding categorical data
    
    
    from sklearn.preprocessing import OneHotEncoder, LabelEncoder
    
    from sklearn.compose import ColumnTransformer
    
    label_encoder_x_1 = LabelEncoder()
    X[: , 2] = label_encoder_x_1.fit_transform(X[:,2])
    transformer = ColumnTransformer(
        transformers=[
            ("OneHot",        # Just a name
             OneHotEncoder(), # The transformer class
             [1]              # The column(s) to be applied on.
             )
        ],
        remainder='passthrough' # donot apply anything to the remaining columns
    )
    X = transformer.fit_transform(X.tolist())
    X = X.astype('float64')
    X = X[:, 1:]
    
    # Splitting the dataset into the Training set and Test set
    from sklearn.model_selection import train_test_split
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
    
    #print(sum(y_train))
    #print(sum(y_test))
    
    # Feature Scaling
    from sklearn.preprocessing import StandardScaler
    sc = StandardScaler()
    X_train = sc.fit_transform(X_train)
    X_test = sc.transform(X_test)
    
    #importing keras 
    import keras
    from keras.models import Sequential
    from keras.layers import Dense
    # Fitting classifier to the Training set
    # Create your classifier here
    classifier = Sequential()
    classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', input_dim = 11))
    classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu'))
    classifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))
    
    classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
    
    classifier.fit(X_train, y_train, batch_size = 10, epochs = 10) 
    # Predicting the Test set results
    y_pred = classifier.predict_classes(X_test)
    #print(classifier.predict(X_test))
    #print(y_pred)
    
    
    # Making the Confusion Matrix
    from sklearn.metrics import confusion_matrix
    from sklearn.metrics import classification_report
    #cm = confusion_matrix(y_test, y_pred)
    
    print(confusion_matrix(y_test, y_pred, labels=[0, 1]))
    print(classification_report(y_test, y_pred, target_names=['0', '1']))
    

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 2022-06-14
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      相关资源
      最近更新 更多