小编Kyl*_*oN-的帖子

如何使用从训练过的keras模型中提取的张量流模型

我想使用keras框架构建和训练神经网络.我配置keras它将使用Tensorflow作为后端.在我使用keras训练模型后,我尝试仅使用Tensorflow.我可以访问会话并获取张量流图.但我不知道如何使用张量流图来进行预测.

我使用以下教程构建了一个网络 http://machinelearningmastery.com/tutorial-first-neural-network-python-keras/

在train()方法中,我仅使用keras构建和训练模型并保存keras和tensorflow模型

在eval()方法中

这是我的代码:

from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
import keras.backend.tensorflow_backend as K
import tensorflow as tf
import numpy

sess = tf.Session()
K.set_session(sess)

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]


def train():
    # create model
    model = Sequential()
    model.add(Dense(12, input_dim=8, init='uniform', activation='relu')) …
Run Code Online (Sandbox Code Playgroud)

python machine-learning neural-network keras tensorflow

9
推荐指数
1
解决办法
3508
查看次数

keras使用中间层的输出

我训练了模型A,并尝试将名称为“ layer_x”的中间层的输出用于模型B中的其他输入。

我试图像在keras doc https://keras.io/getting-started/faq/#how-can-i-obtain-the-output-of-an-intermediate-layer上一样使用中间层的输出

模型A:

inputs = Input(shape=(100,))
dnn = Dense(1024, activation='relu')(inputs)
dnn = Dense(128, activation='relu', name="layer_x")(dnn)
dnn = Dense(1024, activation='relu')(dnn)
output = Dense(10, activation='softmax')(dnn)
Run Code Online (Sandbox Code Playgroud)

型号B:

input_1 = Input(shape=(200,))
input_2 = Input(shape=(100,)) # input for model A

# loading model A
model_a = keras.models.load_model(path_to_saved_model_a)

intermediate_layer_model = Model(inputs=model_a.input, 
                                 outputs=model_a.get_layer("layer_x").output)

intermediate_output = intermediate_layer_model.predict(data)

merge_layer = concatenate([input_1, intermediate_output])
dnn_layer = Dense(512, activation="relu")(merge_layer)
output = Dense(5, activation="sigmoid")(dnn_layer)
model = keras.models.Model(inputs=[input_1, input_2], outputs=output)
Run Code Online (Sandbox Code Playgroud)

当我调试时,在此行出现错误:

intermediate_layer_model = Model(inputs=model_a.input, 
                                 outputs=model_a.get_layer("layer_x").output)

File "..", line 89, in …
Run Code Online (Sandbox Code Playgroud)

python neural-network keras tensorflow

8
推荐指数
1
解决办法
9909
查看次数

如何计算多标签分类的 F1-Score?

我尝试计算f1_score但在使用 sklearnf1_score方法时在某些情况下会收到一些警告。

我有一个预测的多标签 5 类问题。

import numpy as np
from sklearn.metrics import f1_score

y_true = np.zeros((1,5))
y_true[0,0] = 1 # => label = [[1, 0, 0, 0, 0]]

y_pred = np.zeros((1,5))
y_pred[:] = 1 # => prediction = [[1, 1, 1, 1, 1]]

result_1 = f1_score(y_true=y_true, y_pred=y_pred, labels=None, average="weighted")

print(result_1) # prints 1.0

result_2 = f1_score(y_true=y_ture, y_pred=y_pred, labels=None, average="weighted")

print(result_2) # prints: (1.0, 1.0, 1.0, None) for precision/recall/fbeta_score/support
Run Code Online (Sandbox Code Playgroud)

当我使用average="samples"而不是"weighted"我得到 (0.1, 1.0, 0.1818 …

metrics scikit-learn multilabel-classification precision-recall

6
推荐指数
1
解决办法
1万
查看次数

导出Python TensorFlow模型并将其导入C++

我按照本教程尝试根据自己的需要进行更改.我有一个python文件,我训练模型并保存TensorFlow图和frozen_graph,它应该具有权重和体系结构.我有一个C++文件,我在其中阅读frozen_graph并尝试预测一个例子.

// The session will initialize the outputs
vector<Tensor> outputs;
// Run the session, evaluating our "softmax" operation from the graph
status = session->Run(inputs, {"output_TT"}, {}, &outputs);
int nHits = 0;
int nClasses = 2;
for (vector<Tensor>::iterator it = outputs.begin(); it != outputs.end(); ++it) {
    auto items = it->shaped<float, 2>({nTests, nClasses}); // 2 represent number of class
    for (int i = 0; i < nTests; i++) {
        int arg_max = 0;
        float val_max = items(i, 0);
Run Code Online (Sandbox Code Playgroud)

但是当我尝试检索从预测结果我只得到NaN …

c++ python neural-network tensorflow

5
推荐指数
0
解决办法
2365
查看次数

keras结合了预训练模型

我训练了一个模型并希望使用功能性api将其与另一个keras模型相结合(后端是tensorflow版本1.4)

我的第一个模型看起来像这样:

import tensorflow.contrib.keras.api.keras as keras

model = keras.models.Sequential()
input = Input(shape=(200,))
dnn = Dense(400, activation="relu")(input)
dnn = Dense(400, activation="relu")(dnn)
output = Dense(5, activation="softmax")(dnn)
model = keras.models.Model(inputs=input, outputs=output)
Run Code Online (Sandbox Code Playgroud)

在我训练这个模型后,我使用keras model.save()方法保存它.我也可以加载模型并重新训练它没有问题.

现在我想使用此模型的输出作为第二个模型的附加输入:

# load first model
old_model = keras.models.load_model(path_to_old_model)

input_1 = Input(shape=(200,))
input_2 = Input(shape=(200,))
output_old_model = old_model(input_2)

merge_layer = concatenate([input_1, output_old_model])
dnn_layer = Dense(200, activation="relu")(merge_layer)
dnn_layer = Dense(200, activation="relu")(dnn_layer)
output = Dense(10, activation="sigmoid")(dnn_layer)
new_model = keras.models.Model(inputs=[input_1, input_2], outputs=output)
new_model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]
new_model.fit(inputs=[x1,x2], labels=labels, epochs=50, batch_size=32)
Run Code Online (Sandbox Code Playgroud)

当我尝试这个时,我收到以下错误消息:

FailedPreconditionError (see above for …
Run Code Online (Sandbox Code Playgroud)

machine-learning neural-network keras

5
推荐指数
1
解决办法
1446
查看次数

基本数据类型在Java中是原子的

我读到原始数据类型,如布尔,字节,短,字符,整数和浮点数都是原子的。像long和double这样的64位数据类型则不是。

但是,这是什么意思?当我有2个在int变量上递增和递减的线程时,有时我仍会遇到竞态条件。

例如将金额添加到变量的字节码。

getfield #2 <Field int amount>
iload_1
iadd
putfield #2 <Field int amount>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,原子操作是否是每个单个操作(getfield,iadd ...),而不是全部加法?

java atomic race-condition atomicity

2
推荐指数
1
解决办法
760
查看次数

从 beautifulsoup 替换 \n\t

您好,我正在使用 BeautifulSoup 4,我尝试替换汤文本中的“\n\t”字符。

这是我的代码:

soup = BS(html_doc, "html.parser")
for tableItem in soup.find_all("td"):
    result = str(tableItem.string)
    result = result.replace("\n\t\", "")
    print(result)
Run Code Online (Sandbox Code Playgroud)

这是我的输出:

\n', '\t\t\t\t\t\t\t\t\t\tTEXT_I_WANT\t\t\t\t\t\t\t\t\t
Run Code Online (Sandbox Code Playgroud)

我用编码或beautifulsoup“NavigableString”尝试了几件事。我使用了错误的编码吗?或者有没有beautifulsoup的特殊方法。(例如stripped_strings)

ps:我可以替换 TEXT_I_WANT 但不能替换 "\n" 或 "\t"

python replace beautifulsoup special-characters

2
推荐指数
1
解决办法
4853
查看次数

Scala List的cons-operator"::"是否是线程安全的?

cons-operator ::在给定列表上是否是线程安全的?

例如,如果2个线程在同一个列表中使用cons-operator会发生什么?

val listOne = 1::2::3::Nil
val listTwo = 4::5::Nil
val combinedList = listOne ::: listTwo  // thread1
val combinedList2 = listOne ::: 7:8:NIL // thread2 on the same time
Run Code Online (Sandbox Code Playgroud)

multithreading scala race-condition

1
推荐指数
1
解决办法
689
查看次数