经过一些搜索,我仍然无法找到解决方案.我是Keras的新手,如果有解决方案我会道歉并且我实际上不明白它与我的问题有什么关系.
我正在使用Keras 2/Functional API制作一个小型RNN,我无法使Concatenate Layer工作.
这是我的结构:
inputSentence = Input(shape=(30, 91))
sentenceMatrix = LSTM(91, return_sequences=True, input_shape=(30, 91))(inputSentence)
inputDeletion = Input(shape=(30, 1))
deletionMatrix = (LSTM(30, return_sequences=True, input_shape=(30, 1)))(inputDeletion)
fusion = Concatenate([sentenceMatrix, deletionMatrix])
fusion = Dense(122, activation='relu')(fusion)
fusion = Dense(102, activation='relu')(fusion)
fusion = Dense(91, activation='sigmoid')(fusion)
F = Model(inputs=[inputSentence, inputDeletion], outputs=fusion)
Run Code Online (Sandbox Code Playgroud)
这是错误:
ValueError: Unexpectedly found an instance of type `<class 'keras.layers.merge.Concatenate'>`. Expected a symbolic tensor instance.
Run Code Online (Sandbox Code Playgroud)
完整的历史,如果它有助于更多:
Using TensorFlow backend.
str(inputs) + '. All inputs to the layer '
ValueError: Layer dense_1 was called …Run Code Online (Sandbox Code Playgroud) 我无法完全理解Python3x中Type和Value错误之间的区别.
当我尝试使用float('string')而不是TypeError时,为什么会得到ValueError?不应该给出一个TypeError因为我传递一个'str'类型的变量要转换成float?
In [169]: float('string')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-169-f894e176bff2> in <module>()
----> 1 float('string')
ValueError: could not convert string to float: 'string'
Run Code Online (Sandbox Code Playgroud) 这是我拥有的一些代码的简化版本。在第一帧中,用户使用“tk.filedialog”选择一个 csv 文件,该文件将绘制在画布上的同一帧上。
还有第二个框架能够绘制图表,以便在不同的框架上更容易地进行绘制。
运行此版本的代码会导致错误:“ValueError:无效的文件路径或缓冲区对象类型:”。我不确定如何让这段代码在不发生此问题的情况下工作,以便用户选择的文件在带有“a”和“b”列的空图表上绘制。
import csv
import pandas as pd
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
from tkinter import messagebox
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
fig = Figure(figsize=(5,4), dpi=100)
ax= fig.add_subplot(111)
LARGE_FONT= ("Verdana", 12)
class GUI(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "GUI")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (Home, Graph):
frame …Run Code Online (Sandbox Code Playgroud) 我想构建一个评估字符串的 Keras 模型。如果我执行以下操作:
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(units=10, input_shape=(10,), activation='softmax'))
Run Code Online (Sandbox Code Playgroud)
效果很好。我可以看到model.summary().
但是,当我添加图层时ast.literal_eval()
from keras.models import Sequential
from keras.layers import Dense
import ast
model = Sequential()
code = "model.add( Dense( input_shape=(10,), units=10, activation='softmax' ) )"
ast.literal_eval(code)
Run Code Online (Sandbox Code Playgroud)
它让我想到了下一个ValueError:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/ast.py", line 84, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python3.5/ast.py", line 83, in _convert
raise ValueError('malformed node or string: ' + …Run Code Online (Sandbox Code Playgroud) 我已经训练了一个 CNN 并相应地保存了它:
model = Sequential()
model.add(Flatten(input_shape=train_data.shape[1:]))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
loss='binary_crossentropy', metrics=['accuracy'])
model.fit(train_data, train_labels,
epochs=epochs,
batch_size=batch_size,
validation_data=(validation_data, validation_labels))
model.save('full_model.h5')
Run Code Online (Sandbox Code Playgroud)
我现在尝试使用以下命令在另一个 python 脚本中加载模型:
model = tf.keras.models.load_model('full_model.h5')
Run Code Online (Sandbox Code Playgroud)
并收到以下错误:
Traceback (most recent call last):
File "/media/spt/Data/tensorflow_server/get_model.py", line 12, in <module>
model = tf.keras.models.load_model('full_model.h5')
File "/home/spt/.conda/envs/dev_env/lib/python3.6/site-packages/tensorflow/python/keras/engine/saving.py", line 229, in load_model
model = model_from_config(model_config, custom_objects=custom_objects)
File "/home/spt/.conda/envs/dev_env/lib/python3.6/site-packages/tensorflow/python/keras/engine/saving.py", line 306, in model_from_config
return deserialize(config, custom_objects=custom_objects)
File "/home/spt/.conda/envs/dev_env/lib/python3.6/site-packages/tensorflow/python/keras/layers/serialization.py", line 64, in deserialize
printable_module_name='layer')
File "/home/spt/.conda/envs/dev_env/lib/python3.6/site-packages/tensorflow/python/keras/utils/generic_utils.py", line 173, in deserialize_keras_object
list(custom_objects.items())))
File "/home/spt/.conda/envs/dev_env/lib/python3.6/site-packages/tensorflow/python/keras/engine/sequential.py", line 286, …Run Code Online (Sandbox Code Playgroud) 我的数据框包含年,月,日,小时,分钟,秒,Daily_KWH列.我需要使用神经网络来预测每日KWH.请让我知道如何去做
Daily_KWH_System year month day hour minute second
0 4136.900384 2016 9 7 0 0 0
1 3061.657187 2016 9 8 0 0 0
2 4099.614033 2016 9 9 0 0 0
3 3922.490275 2016 9 10 0 0 0
4 3957.128982 2016 9 11 0 0 0
Run Code Online (Sandbox Code Playgroud)
当我适应模型时,我得到了价值错误.
代码到目前为止:
X = df[['year','month','day','hour','minute','second']]
y = df['Daily_KWH_System']
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y)
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
# Fit only to the training …Run Code Online (Sandbox Code Playgroud) classification neural-network model-fitting python-3.x valueerror
我已经看过其他帖子谈论这个,但其中任何一个都可以帮助我.我在Windows x6机器上使用jupyter笔记本和Python 3.6.0.我有一个大型数据集,但我只保留了一部分来运行我的模型:
这是我使用的一段代码:
df = loan_2.reindex(columns= ['term_clean','grade_clean', 'annual_inc', 'loan_amnt', 'int_rate','purpose_clean','installment','loan_status_clean'])
df.fillna(method= 'ffill').astype(int)
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import StandardScaler
imp = Imputer(missing_values='NaN', strategy='median', axis=0)
array = df.values
y = df['loan_status_clean'].values
imp.fit(array)
array_imp = imp.transform(array)
y2= y.reshape(1,-1)
imp.fit(y2)
y_imp= imp.transform(y2)
X = array_imp[:,0:4]
Y = array_imp[:,4]
validation_size = 0.20
seed = 7
X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)
seed = 7
scoring = 'accuracy'
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix …Run Code Online (Sandbox Code Playgroud) 请对我放轻松。我正在将职业转向数据科学,并且没有 CS 或编程背景——所以我可能会做一些非常愚蠢的事情。我已经研究了几个小时没有成功。
目标:让 Pipeline 与 OrdinalEncoder 一起运行。
问题:代码无法在 OrdinalEncoder 调用下运行。它确实在没有 OrdinalEncoder 的情况下运行。作为最好的,我可以告诉我可以通过两个参数,即类和D型。都不帮忙。
我正在将公共糖尿病数据集传递给模型。这是问题吗?IOW,将高基数特征传递给 OrdinalEncoder 是否会在构建模型后导致训练/测试数据之间出现问题,即测试分割具有训练集没有的值?
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OrdinalEncoder
from sklearn.ensemble import RandomForestClassifier
pipe = Pipeline([
('imputer', SimpleImputer()),
('ordinal_encoder', OrdinalEncoder()),
('classifier', RandomForestClassifier(criterion='gini', n_estimators=100))])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# Construct model
model = pipe.fit(X_train, y_train)
# Show results
print("Hold-out AUC score: %.3f" %roc_auc_score(model.predict_proba(X_test),y_test))
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
ValueError: Found unknown categories [17.0] in column 0 …Run Code Online (Sandbox Code Playgroud) 我有问题
ValueError:至少需要一个数组来连接
以下是整个错误消息。
Training mode
Traceback (most recent call last):
File "bcf.py", line 342, in <module>
bcf.train()
File "bcf.py", line 321, in train
self._learn_codebook()
File "bcf.py", line 142, in _learn_codebook
feats_sc = np.concatenate(feats_sc, axis=1).transpose()
ValueError: need at least one array to concatenate
Run Code Online (Sandbox Code Playgroud)
下面是问题的区域。
def _learn_codebook(self):
MAX_CFS = 800 # max number of contour fragments per image; if above, sample randomly
CLUSTERING_CENTERS = 1500
feats_sc = []
for image in self.data.values():
feats = image['cfs']
feat_sc = feats[1]
if feat_sc.shape[1] > MAX_CFS: …Run Code Online (Sandbox Code Playgroud) 即使在回答和评论中应用建议后,看起来尺寸不匹配问题仍然存在。这也是要复制的确切代码和数据文件:https : //drive.google.com/drive/folders/1q67s0VhB-O7J8OtIhU2jmj7Kc4LxL3sf?usp=sharing
这个怎么改啊!?最新代码、模型摘要、使用的函数和我得到的错误如下
type_ae=='dcor'
#Wrappers for keras
def custom_loss1(y_true,y_pred):
dcor = -1*distance_correlation(y_true,encoded_layer)
return dcor
def custom_loss2(y_true,y_pred):
recon_loss = losses.categorical_crossentropy(y_true, y_pred)
return recon_loss
input_layer = Input(shape=(64,64,1))
encoded_layer = Conv2D(filters = 128, kernel_size = (5,5),padding = 'same',activation ='relu',
input_shape = (64,64,1))(input_layer)
encoded_layer = MaxPool2D(pool_size=(2,2))(encoded_layer)
encoded_layer = Dropout(0.25)(encoded_layer)
encoded_layer = (Conv2D(filters = 64, kernel_size = (3,3),padding = 'same',activation ='relu'))(encoded_layer)
encoded_layer = (MaxPool2D(pool_size=(2,2)))(encoded_layer)
encoded_layer = (Dropout(0.25))(encoded_layer)
encoded_layer = (Conv2D(filters = 64, kernel_size = (3,3),padding = 'same',activation ='relu'))(encoded_layer)
encoded_layer = (MaxPool2D(pool_size=(2,2)))(encoded_layer)
encoded_layer = …Run Code Online (Sandbox Code Playgroud) valueerror ×10
python ×8
keras ×4
python-3.x ×2
scikit-learn ×2
csv ×1
dimensions ×1
numpy ×1
ordinal ×1
pandas ×1
pipeline ×1
tensorflow ×1
tkinter ×1
typeerror ×1