Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tensorflow keras矩阵尺寸与极其简单的模型不兼容_Python_Tensorflow_Keras - Fatal编程技术网

Python Tensorflow keras矩阵尺寸与极其简单的模型不兼容

Python Tensorflow keras矩阵尺寸与极其简单的模型不兼容,python,tensorflow,keras,Python,Tensorflow,Keras,我试图用keras编码线性和逻辑模型,并用相同的数据进行训练,但遇到了这个令人困惑的错误。下面是代码和错误消息 将tensorflow导入为tf 从tensorflow导入keras作为tfk 作为pd进口熊猫 def build_模型(n_特性,**kwargs): model=tfk.models.Sequential([ tfk.layers.Dense(1,输入_形状=[n_特征,],**kwargs) ]) optimizer=tfk.optimizers.SGD() compile(

我试图用keras编码线性和逻辑模型,并用相同的数据进行训练,但遇到了这个令人困惑的错误。下面是代码和错误消息

将tensorflow导入为tf
从tensorflow导入keras作为tfk
作为pd进口熊猫
def build_模型(n_特性,**kwargs):
model=tfk.models.Sequential([
tfk.layers.Dense(1,输入_形状=[n_特征,],**kwargs)
])
optimizer=tfk.optimizers.SGD()
compile(loss=model,optimizer=optimizer,metrics=[tfk.metrics.binary\u-accurity])
回归模型
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
数据=获取数据()
第x列、第y列、测试第x列、测试第y列=过程数据(数据)
类PrintDot(tfk.callbacks.Callback):
纪元结束时的def(自身、纪元、日志):
如果历元%100==0:
打印(“”)
打印('.',结束='')
纪元=1000
批次大小=无
d=长度(列×键())
线性=构建模型(d)
sigmoid=build\u模型(d,activation=tfk.activations.sigmoid)
打印(列车形状)
打印(序列y.形状)
打印(测试形状)
打印(测试y.形状)
打印(linear.summary())
打印(sigmoid.summary())
线性_res=linear.fit(
第x列,第y列,批次尺寸=批次尺寸,
epochs=epochs,validation_split=0.2,verbose=0,
回调=[PrintDot()])
sigmoid_res=sigmoid.fit(
第x列,第y列,批次尺寸=批次尺寸,
epochs=epochs,validation_split=0.2,verbose=0,
回调=[PrintDot()])
损失线性,acc线性=线性。评估(测试x,测试y,详细=0)
损失乙状结肠,附件乙状结肠=乙状结肠。评估(测试x,测试y,详细=0)
打印(“”)
线性:损失={.2f}精度={.2f}
逻辑:损失={.2f}精度={.2f}
“.”格式(丢失\u线性、acc\u线性、丢失\u S形、acc\u S形))
这里是数据和模型摘要的形状,看起来一点也不错

(736, 15)
(736,)
(184, 15)
(184,)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 1)                 16        
=================================================================
Total params: 16
Trainable params: 16
Non-trainable params: 0
_________________________________________________________________
None
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_1 (Dense)              (None, 1)                 16        
=================================================================
Total params: 16
Trainable params: 16
Non-trainable params: 0
_________________________________________________________________
None

这产生了一个错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [32,1], In[1]: [15,1]
     [[{{node loss/dense_loss/sequential/dense/MatMul}}]]
     [[{{node ConstantFoldingCtrl/loss/dense_loss/broadcast_weights/assert_broadcastable/AssertGuard/Switch_0}}]]
我认为32是默认的批处理大小,15是数据的维度/列,但为什么会有[15,1]的数组呢

以下是来自tensorflow的详细错误消息:

2019-07-09 14:47:57.381250: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2019-07-09 14:47:57.636045: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1433] Found device 0 with properties: 
name: GeForce GTX 1060 major: 6 minor: 1 memoryClockRate(GHz): 1.6705
pciBusID: 0000:01:00.0
totalMemory: 6.00GiB freeMemory: 4.97GiB
2019-07-09 14:47:57.636491: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-07-09 14:47:58.354913: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-07-09 14:47:58.355175: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0 
2019-07-09 14:47:58.355332: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N 
2019-07-09 14:47:58.355663: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 4716 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1060, pci bus id: 0000:01:00.0, compute capability: 6.1)
2019-07-09 14:47:58.953351: I tensorflow/stream_executor/dso_loader.cc:152] successfully opened CUDA library cublas64_100.dll locally
2019-07-09 14:47:59.396889: E tensorflow/stream_executor/cuda/cuda_blas.cc:510] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2019-07-09 14:47:59.397449: E tensorflow/stream_executor/cuda/cuda_blas.cc:510] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2019-07-09 14:47:59.399714: E tensorflow/stream_executor/cuda/cuda_blas.cc:510] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2019-07-09 14:47:59.402435: E tensorflow/stream_executor/cuda/cuda_blas.cc:510] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2019-07-09 14:47:59.402714: W tensorflow/stream_executor/stream.cc:2130] attempting to perform BLAS operation using StreamExecutor without BLAS support
Traceback (most recent call last):
  File "C:/Users/charl/PycharmProjects/cs229_models/keras_logistic_regression.py", line 168, in <module>
    callbacks=[PrintDot()])
  File "C:\Users\charl\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py", line 880, in fit
    validation_steps=validation_steps)
  File "C:\Users\charl\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py", line 329, in model_iteration
    batch_outs = f(ins_batch)
  File "C:\Users\charl\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\keras\backend.py", line 3076, in __call__
    run_metadata=self.run_metadata)
  File "C:\Users\charl\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\client\session.py", line 1439, in __call__
    run_metadata_ptr)
  File "C:\Users\charl\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 528, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [32,1], In[1]: [15,1]
     [[{{node loss/dense_loss/sequential/dense/MatMul}}]]
     [[{{node ConstantFoldingCtrl/loss/dense_loss/broadcast_weights/assert_broadcastable/AssertGuard/Switch_0}}]]
2019-07-09 14:47:57.381250:I tensorflow/core/platform/cpu\u feature\u guard.cc:141]您的cpu支持未编译此tensorflow二进制文件以使用的指令:AVX AVX2
2019-07-09 14:47:57.636045:I tensorflow/core/common_runtime/gpu/gpu_device.cc:1433]找到了具有以下属性的设备0:
名称:GeForce GTX 1060大调:6小调:1记忆锁定速率(GHz):1.6705
pciBusID:0000:01:00.0
总内存:6.00GiB自由内存:4.97GiB
2019-07-09 14:47:57.636491:I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512]添加可见gpu设备:0
2019-07-09 14:47:58.354913:I tensorflow/core/common_runtime/gpu/gpu_device.cc:984]设备互连拖缆执行器,带强度1边缘矩阵:
2019-07-09 14:47:58.355175:I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]0
2019-07-09 14:47:58.355332:I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003]0:N
2019-07-09 14:47:58.355663:I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115]创建tensorflow设备(/job:localhost/replica:0/task:0/device:gpu:0,4716MB内存)->物理gpu(设备:0,名称:GeForce GTX 1060,pci总线id:0000:01:00.0,计算能力:6.1)
2019-07-09 14:47:58.953351:I tensorflow/stream_executor/dso_loader.cc:152]在本地成功打开CUDA库cublas64_100.dll
2019-07-09 14:47:59.396889:E tensorflow/stream_executor/cuda/cuda_blas.cc:510]未能创建cublas句柄:cublas_状态_ALLOC_失败
2019-07-09 14:47:59.397449:E tensorflow/stream_executor/cuda/cuda_blas.cc:510]未能创建cublas句柄:cublas_状态_ALLOC_失败
2019-07-09 14:47:59.399714:E tensorflow/stream_executor/cuda/cuda_blas.cc:510]无法创建cublas句柄:cublas_STATUS_ALLOC_失败
2019-07-09 14:47:59.402435:E tensorflow/stream_executor/cuda/cuda_blas.cc:510]未能创建cublas句柄:cublas_状态_ALLOC_失败
2019-07-09 14:47:59.402714:W tensorflow/stream_executor/stream.cc:2130]试图在没有BLAS支持的情况下使用StreamExecutor执行BLAS操作
回溯(最近一次呼叫最后一次):
文件“C:/Users/charl/PycharmProjects/cs229_models/keras_logistic_regression.py”,第168行,在
回调=[PrintDot()])
文件“C:\Users\charl\Anaconda3\envs\tensorflow gpu\lib\site packages\tensorflow\python\keras\engine\training.py”,第880行,格式为fit
验证步骤=验证步骤)
文件“C:\Users\charl\Anaconda3\envs\tensorflow gpu\lib\site packages\tensorflow\python\keras\engine\training\u arrays.py”,第329行,在模型迭代中
批量输出=f(批量输入)
文件“C:\Users\charl\Anaconda3\envs\tensorflow gpu\lib\site packages\tensorflow\python\keras\backend.py”,第3076行,在调用中__
run\u元数据=self.run\u元数据)
文件“C:\Users\charl\Anaconda3\envs\tensorflow gpu\lib\site packages\tensorflow\python\client\session.py”,第1439行,在\uuu调用中__
运行_元数据_ptr)
文件“C:\Users\charl\Anaconda3\envs\tensorflow gpu\lib\site packages\tensorflow\python\framework\errors\u impl.py”,第528行,在退出中__
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors\u impl.InvalidArgumentError:矩阵大小不兼容:在[0]:[32,1],在[1]:[15,1]
[{{node loss/densite_loss/sequential/densite/MatMul}}]
[{{node ConstantFoldingCtrl/loss/densite_loss/broadcast_weights/assert_broadcastable/AssertGuard/Switch_0}}]

也许我误解了什么,但您在编译时编写
model.compile(loss=model…
的原因是什么?我的理解是,
keras
中的损失函数总是希望输入形式为
loss\u函数(y\u true,y\u pred)

正如您所说,
[32,1]
是一批
序列数据的形状,
[15,1]
是模型输入的形状(您将其用作
!pip install tensorflow-gpu==1.14.0
import tensorflow as tf
import numpy as np

import tensorflow as tf
from tensorflow import keras as tfk
import pandas as pd

print(tf.__version__)


def build_model(n_features, **kwargs):
    model = tfk.models.Sequential([
        tfk.layers.Dense(1, input_shape=[n_features, ], **kwargs)
    ])
    optimizer = tfk.optimizers.SGD()
    model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=[tfk.metrics.binary_accuracy])
    return model


train_x = np.random.rand(736, 15)
train_y = np.random.rand(736,)


class PrintDot(tfk.callbacks.Callback):
    def on_epoch_end(self, epoch, logs):
        if epoch % 100 == 0:
            print('')
        print('.', end='')


EPOCHS = 1000
BATCH_SIZE = None
d = train_x.shape[1]

linear = build_model(d)
sigmoid = build_model(d, activation=tfk.activations.sigmoid)

print(train_x.shape)
print(train_y.shape)
print(linear.summary())
print(sigmoid.summary())

linear_res = linear.fit(
    train_x, train_y, batch_size=BATCH_SIZE,
    epochs=EPOCHS, validation_split=0.2, verbose=0,
    callbacks=[PrintDot()])
sigmoid_res = sigmoid.fit(
    train_x, train_y, batch_size=BATCH_SIZE,
    epochs=EPOCHS, validation_split=0.2, verbose=0,
    callbacks=[PrintDot()])
train_x = np.random.rand(736, 15)
train_y = np.random.rand(736,)