windows - Python spyder + tensorflow 交叉验证在 Windows 10 上冻结
问题描述
在 Windows 10 上,我已经安装Anaconda
并启动了Spyder
. 我也成功安装了Theano
,Tensorflow
并且Keras
,自从我执行
导入 keras
控制台输出
使用 TensorFlow 后端
当我编译并拟合神经网络时,它运行良好。但是,当我尝试运行 k 折交叉验证,通过 keras 包装器结合 scikit-learn 并使用参数 n_jobs = -1 (通常 n_jobs 具有任何值,因此具有多处理)时,控制台将永远冻结,直到重新启动内核手动或终止 Spyder。
另一个问题,当我尝试使用 GridSearchCV 运行一些参数调整时,即 100 个时期,它不会冻结,但它输出 1/1 而不是 1/100 时期,通常它给出的结果不好,不合逻辑(即它只运行几分钟,而通常需要几个小时!)。
我的代码是:
# Part 1 - Data Preprocessing
# 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
# Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
# Avoiding the dummy variable trap
X = X[:, 1:]
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation 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)
# Part 2 - Now let's make the ANN!
# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
# Initialising the ANN
classifier = Sequential()
# Adding the input layer and the first hidden layer with dropout
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
classifier.add(Dropout(rate = 0.1)) # p should vary from 0.1 to 0.4, NOT HIGHER, because then we will have under-fitting.
# Adding the second hidden layer with dropout
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
classifier.add(Dropout(rate = 0.1))
# Adding the output layer
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
# Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Fitting the ANN to the Training set
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)
# Part 3 - Making predictions and evaluating the model
# Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
new_prediction = classifier.predict(sc.transform(np.array([[0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]])))
new_prediction = (new_prediction > 0.5)
#Part 4 = Evaluating, Improving and Tuning the ANN
# Evaluating the ANN
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
from keras.models import Sequential
from keras.layers import Dense
def build_classifier():
classifier = Sequential()
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
return classifier
classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, nb_epoch = 100)
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)
mean = accuracies.mean()
variance = accuracies.std()
# Improving the ANN
# Tuning the ANN
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
from keras.models import Sequential
from keras.layers import Dense
def build_classifier(optimizer):
classifier = Sequential()
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
classifier.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy'])
return classifier
classifier = KerasClassifier(build_fn = build_classifier)
parameters = {"batch_size": [25, 32],
"nb_epoch": [100, 500],
"optimizer": ["adam", "rmsprop"]}
grid_search = GridSearchCV(estimator = classifier,
param_grid = parameters,
scoring = "accuracy",
cv = 10)
grid_search = grid_search.fit(X_train, y_train)
best_parameters = grid_search.best_params_
best_accuracy = grid_search.best_score_
此外,对于 n_jobs = 1,它运行但说 epoch 1/1 并运行 10 次,这是 k 倍值。这意味着它识别 nb_epoch = 1 而不是 100 出于某种原因。最后,我尝试将 cross_val_score() 包含在一个类中:
class run():
def __init__(self):
cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)
if __name__ == '__main__':
run()
或仅在 if 条件下使用:
if __name__ == '__main__':
cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)
但它也不起作用,它再次冻结。
谁能帮我解决这些问题?发生了什么事,我能做些什么来解决这些问题,以便一切正常运行?先感谢您。
解决方案
似乎 Windows 的“n_jobs”有问题,在你的“accuracies=”代码中删除它,它会起作用,缺点是它可能需要一段时间,但至少它会起作用。
推荐阅读
- java - 使用 Jackson 反序列化派生类
- multiprocessing - 每个多处理器内核的独立指令存储器
- java - Hibernate/JPA 合并(更新)问题
- javascript - 将 id 和 class 传递给 js 方法
- python - scipy.fftpack 的 FFT 冻结
- eclipse-plugin - Eclipse(JBoss 工具)和 DevStudio 中缺少 LiveReload 服务器
- tensorflow - 如何规范化张量流中模型的输入数据
- android - 将光标放在 setHint TextView android 之后
- python - 如何在pyspark中生成带有数量的关联规则?
- python - 使用 OpenCv 流式传输视频错误