Ожидаемый float64 передан параметру 'y' операции 'Equal', вместо этого получил 'коллекции' типа 'str' - PullRequest
0 голосов
/ 18 июня 2020

Я не нашел других вопросов по этому же топи c, кроме одного, сообщившего об этом как об ошибке еще в 2018 году, которая, как мне кажется, уже решена.

predictions = model(x_true, training=True)

Печать x_true из здесь показывает, что это правильный тип dtype, однако возникает ошибка:

learning.py: 121 train_step * predictions = model (images, training = True) learning.py:100 call * x = self.input1 (x) C: \ Users \ Benjamin \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ tensorflow \ python \ ops \ math_ops.py: 1491 tensor_equals ** return gen_math_ops.equal (self, other, incompatible_shape_error = False) C: \ Users \ Benjamin \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ tensorflow \ python \ ops \ gen_math_ops.py: 3224 равное имя = имя) C: \ Users \ Benjamin \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ tensorflow \ python \ framework \ op_def_library.py: 479 _apply_op_helper repr (значения), тип (значения). имя , err))

TypeError: Expected float64 passed to parameter 'y' of op 'Equal', got 'collections' of type 'str' instead. Error: Expected float64, got 'collections' of type 'str' instead.

Мой полный код:

import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'
import tensorflow as tf
from tensorflow_probability import distributions as tfd
from tensorflow.keras.layers import Dense, Flatten, Conv2D, Input, LSTM, Concatenate
from tensorflow.keras import Model
import numpy as np

f = open("datasets.txt", "r+")
txt = f.read()
allData = txt.split("|")[:1000]
x_train = []
y_train = []
val_split = 0.8
buys = 0
highest = -1000.0
lowest = 1000.0
sells = 0
for i in range(len(allData)):
    newArr = allData[i].split(",")
    newPriceArr = []
    y_train.append(float(newArr[-1]))
    if(float(newArr[-1])>highest):
        highest = float(newArr[-1])
    if(float(newArr[-1])<lowest):
        lowest = float(newArr[-1])
    maxN = float(max(newArr[:-1]))
    minN = float(min(newArr[:-1]))
    for j in range(36):
        newPriceArr.append([(float(newArr[j])-minN)/(maxN-minN)])
    x_train.append(newPriceArr)
x_all = x_train
y_all = y_train
val_split_n = int(len(x_all)*val_split)
x_train = x_all[:val_split_n]
y_train = y_all[:val_split_n]
x_test = x_all[val_split_n:]
y_test = y_all[val_split_n:]
x_train = np.array(x_train)
x_test = np.array(x_test)
y_train = np.array(y_train)
y_test = np.array(y_test)

print(x_train.dtype)

def slice_parameter_vectors(parameter_vector):

    return [parameter_vector[:,i*dist_components:(i+1)*dist_components] for i in range(3)]

def gnll_loss(y, parameter_vector):

    alpha, mu, sigma = slice_parameter_vectors(parameter_vector)
    alpha = tf.reshape(alpha, [-1])
    mu = tf.reshape(mu, [-1])
    sigma = tf.reshape(sigma, [-1])

    plusOne = tf.constant([1.])


    gm = tfd.MixtureSameFamily(
        mixture_distribution=tfd.Categorical(probs=tf.math.add(alpha, plusOne)),#tfd.Categorical(probs=alpha),
        components_distribution=tfd.Normal(
            loc=mu,
            scale=tf.math.add(plusOne, sigma)))
    log_likelihood = gm.log_prob(tf.transpose(y))

    return -tf.reduce_mean(log_likelihood, axis=-1)

tf.keras.backend.set_floatx('float64')

class MyModel(Model):
    def __init__(self, dist_components):
        super(MyModel, self).__init__()
        self.input1 = Input(shape=(36,1), name="Input")
        self.lstm1 = LSTM(1, activation="relu", return_sequences=False, name="LSTM1", kernel_initializer="he_uniform")
        self.lstm2 = LSTM(1, activation="relu", return_sequences=False, name="LSTM1", kernel_initializer="he_uniform")
        self.alphas = Dense(dist_components, activation="elu", name="alphas")
        self.mus = Dense(dist_components, activation = "tanh", name="mus")
        self.sigmas = Dense(dist_components, activation="elu", name="sigmas")

    def call(self, x):
        print("call:",x)
        x = self.input1(x)
        x = self.lstm1(x)
        x = self.lstm2(x)
        a = self.alphas(x)
        b = self.mus(x)
        c = self.sigmas(x)
        return Concatenate(name="output")([a,b,c])

model = MyModel(2)

loss_object = gnll_loss
optimizer = tf.keras.optimizers.Adam()

train_loss = tf.keras.metrics.Mean(name="train_loss")
test_loss = tf.keras.metrics.Mean(name="test_loss")

@tf.function
def train_step(x_true, y_true):
    with tf.GradientTape() as tape:
        predictions = model(x_true, training=True)
        loss = loss_object(y_true, predictions)
    gradients = tape.gradient(loss, model.trainable_variables)
    optimizer.apply_gradients(zip(gradients, model.trainable_variables))

    train_loss(loss)

@tf.function
def test_step(x_true, y_true):
    predictions = model(x_true, training=False)
    loss = loss_object(y_true, predictions)

    test_loss(loss)

EPOCHS = 5
for epoch in range(EPOCHS):
    train_loss.reset_states()
    test_loss.reset_states()

    for trainI in range(len(x_train)):
        train_step(x_train[trainI], y_train[trainI])

    for testI in range(len(x_test)):
        test_step(x_test[testI], y_test[testI])

    template = "Epoch: {}, Train loss: {}, Test loss: {}"
    print(temaplte.format(epoch+1, train_loss.result(), test_loss.result()))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...