小编Nic*_*ais的帖子

层 lstm_5 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2

我正在尝试创建一个图像字幕模型。你能帮忙解决这个错误吗?input1 是图像向量,input2 是字幕序列。32 是字幕长度。我想将图像向量与序列的嵌入连接起来,然后将其提供给解码器模型。


    def define_model(vocab_size, max_length):
      input1 = Input(shape=(512,))
      input1 = tf.keras.layers.RepeatVector(32)(input1)
      print(input1.shape)

      input2 = Input(shape=(max_length,))
      e1 = Embedding(vocab_size, 512, mask_zero=True)(input2)
      print(e1.shape)

      dec1 = tf.concat([input1,e1], axis=2)
      print(dec1.shape)

      dec2 = LSTM(512)(dec1)
      dec3 = LSTM(256)(dec2)
      dec4 = Dropout(0.2)(dec3)
      dec5 = Dense(256, activation="relu")(dec4)
      output = Dense(vocab_size, activation="softmax")(dec5)
      model = tf.keras.Model(inputs=[input1, input2], outputs=output)
      model.compile(loss="categorical_crossentropy", optimizer="adam")
      print(model.summary())
      return model

Run Code Online (Sandbox Code Playgroud)
ValueError: Input 0 of layer lstm_5 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 512]
Run Code Online (Sandbox Code Playgroud)

python nlp lstm keras tensorflow

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

如何使用 Tensorflow2 (jupyter, Win) 杀死 tensorboard

对于菜鸟问题​​很抱歉,但是我如何杀死 Tensorflow PID?

它说:

Reusing TensorBoard on port 6006 (pid 5128), started 4 days, 18:03:12 ago. (Use '!kill 5128' to kill it.)

但是我在 windows taks 管理器中找不到任何 PID 5128。在 jupyter 中使用 '!kill 5128' 错误返回找不到命令 kill 。在 Windows cmd 或 conda cmd 中使用它也不起作用。

谢谢你的帮助。

python tensorflow tensorboard

7
推荐指数
2
解决办法
6442
查看次数

在 sklearn 中可视化决策树

当我想可视化这棵树时,我收到了这个错误。

我已经展示了导入的所需库。jupiter-notebook 有预期的原因吗?

from sklearn import tree
import matplotlib.pyplot
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
cancer=load_breast_cancer()
x=cancer.data
y=cancer.target
clf=DecisionTreeClassifier(max_depth=1000)
x_train,x_test,y_train,y_test=train_test_split(x,y)
clf=clf.fit(x_train,y_train)
tree.plot_tree(clf.fit(x_train,y_train))
Run Code Online (Sandbox Code Playgroud)

AttributeError: 模块“sklearn.tree”没有属性“plot_tree”

python tree sklearn-pandas jupyter-notebook

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

Pytorch CNN无法学习,需要帮助找出原因

我正在与Pytorch进行CNN任务,但它不会学习并不能提高准确性。我与MNIST一起制作了一个版本,因此可以在此处发布。我只是在寻找为什么它不起作用的答案。该体系结构很好,我在Keras中实现了它,经过3个星期,我的准确率超过了92%。注意:我将MNIST重塑为60x60图片,因为这是我的“真实”问题中的图片。

import numpy as np
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.autograd import Variable
from keras.datasets import mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()


def resize(pics):
    pictures = []
    for image in pics:
        image = Image.fromarray(image).resize((dim, dim))
        image = np.array(image)
        pictures.append(image)
    return np.array(pictures)


dim = 60

x_train, x_test = resize(x_train), resize(x_test) # because my real problem is in 60x60

x_train = x_train.reshape(-1, 1, …
Run Code Online (Sandbox Code Playgroud)

python conv-neural-network pytorch

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

ValueError:层序的输入 0 与层不兼容::预期 min_ndim=4,发现 ndim=3。收到的完整形状:[8, 28, 28]

我不断收到与输入形状相关的错误。任何帮助将不胜感激。谢谢!

import tensorflow as tf

(xtrain, ytrain), (xtest, ytest) = tf.keras.datasets.mnist.load_data()

model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(16, kernel_size=3, activation='relu'),
    tf.keras.layers.MaxPooling2D(pool_size=2),
    tf.keras.layers.Conv2D(32, kernel_size=3, activation='relu'),
    tf.keras.layers.MaxPooling2D(pool_size=2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
    ])

model.compile(loss='categorical_crossentropy', 
              optimizer='adam',
              metrics='accuracy')

history = model.fit(xtrain, ytrain,
                    validation_data=(xtest, ytest),
                    epochs=10, batch_size=8)
Run Code Online (Sandbox Code Playgroud)

ValueError:层序的输入 0 与层不兼容::预期 min_ndim=4,发现 ndim=3。收到的完整形状:[8, 28, 28]

python deep-learning keras tensorflow

7
推荐指数
2
解决办法
2万
查看次数

Python:查找视频中的笔迹数量

你知道有一种算法可以看出图像上有笔迹吗?我没兴趣知道字迹写的是什么,只知道有一个礼物?

我有一段有人用手写填充幻灯片的视频。我的目标是确定幻灯片中已经填充了多少手写内容。

在此处输入图片说明

有问题的视频可以在这里下载:http : //www.filedropper.com/00_6

对于这个特定的视频,量化幻灯片中手写的内容已经提出了一个很好的解决方案

该解决方案基于将用于手写的特定颜色的数量相加。但是,如果笔迹不是蓝色而是在非笔迹上也可以找到的任何其他颜色,则此方法将不起作用。

因此,我很想知道,是否存在更通用的解决方案来确定图像上是否存在笔迹?

到目前为止我所做的: 我正在考虑提取图像的轮廓,然后根据轮廓的弯曲程度以某种方式检测手写部分(但我不知道如何做那部分)。不过,这可能不是最好的主意,因为它并不总是正确的......

import cv2
import matplotlib.pyplot as plt



img = cv2.imread(PATH TO IMAGE)
print("img shape=", img.shape)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

cv2.imshow("image", gray)
cv2.waitKey(1)
#### extract all contours
# Find Canny edges 
edged = cv2.Canny(gray, 30, 200) 
cv2.waitKey(0) 
  
# Finding Contours 
# Use a copy of the image e.g. edged.copy() 
# since findContours alters the image 
contours, hierarchy = cv2.findContours(edged,  
    cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 
  
cv2.imshow('Canny Edges After Contouring', edged) …
Run Code Online (Sandbox Code Playgroud)

python opencv numpy image-processing computer-vision

7
推荐指数
2
解决办法
566
查看次数

如何从 Anaconda 提示符安装 Python 3.9?

据官网消息,Python 3.9.0rc1 已于今日发布。

有什么方法可以在 Anaconda 环境中使用它吗?我试过

conda create --name python39 python==3.9
Run Code Online (Sandbox Code Playgroud)

但它说:

错误:找不到满足 python==3.9 要求的版本(来自版本:无)错误:找不到 python==3.9 的匹配发行版

编辑:作为重复项关闭排除了没有答案的问题,并且对建议的重复项的自我接受的答案并没有回答问题。它说“改用其他分销渠道”。

python anaconda conda python-3.9

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

如何使用 Numpy 对字符串数组进行一次性编码?

我知道那里有次优的解决方案,但我正在尝试优化我的代码。到目前为止,我发现的最短方法是:

import numpy as np
from sklearn.preprocessing import OrdinalEncoder

target = np.array(['dog', 'dog', 'cat', 'cat', 'cat', 'dog', 'dog', 'cat', 'cat'])

oe = OrdinalEncoder()
target = oe.fit_transform(target.reshape(-1, 1)).ravel()
target = np.eye(np.unique(target).shape[0])[np.array(target, dtype=np.int32)]
print(target)
Run Code Online (Sandbox Code Playgroud)

[[0。1.]
[0。1.]
[1. 0.]
[1. 0.]
...

这是丑陋的代码,而且很长。删除它的任何部分,它就不起作用。我正在寻找一种更简单的方法,该方法不会涉及从两个不同的库调用六个以上的函数。

python numpy

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

在 Pytorch 卷积神经网络中展平张量(大小不匹配错误)

我用随机像素做了一个可重复的例子。我试图在卷积层之后展平密集层的张量。问题出在卷积层和密集层的交叉处。我不知道如何放置正确数量的神经元。

tl;dr我正在寻找等效的手册keras.layers.Flatten()因为它不存在于pytorch.

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader

x = np.random.rand(1_00, 3, 100, 100)
y = np.random.randint(0, 2, 1_00)

if torch.cuda.is_available():
    x = torch.from_numpy(x.astype('float32')).cuda()
    y = torch.from_numpy(y.astype('float32')).cuda()

class ConvNet(nn.Module):

    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 32, 3)
        self.conv2 = nn.Conv2d(32, 64, 3)
        self.conv3 = nn.Conv2d(64, 128, 3)

        self.fc1 = nn.Linear(128, 1024) # 128 …
Run Code Online (Sandbox Code Playgroud)

python conv-neural-network pytorch tensor

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

如何使用accuracy_score(或其他建议的函数)测量xgboost回归器的准确性

我正在编写代码来解决一个简单的问题,即预测库存中物品丢失的概率。

我正在使用XGBoost预测模型来做到这一点。

我将数据分成两个 .csv 文件,一个是训练数据,另一个是测试数据

这是代码:

    import pandas as pd
    import numpy as np


    train = pd.read_csv('C:/Users/pedro/Documents/Pedro/UFMG/8o periodo/Python/Trabalho Final/train.csv', index_col='sku').fillna(-1)
    test = pd.read_csv('C:/Users/pedro/Documents/Pedro/UFMG/8o periodo/Python/Trabalho Final/test.csv', index_col='sku').fillna(-1)


    X_train, y_train = train.drop('isBackorder', axis=1), train['isBackorder']

    import xgboost as xgb
    xg_reg = xgb.XGBRegressor(objective ='reg:linear', colsample_bytree = 0.3, learning_rate = 0.1,
                    max_depth = 10, alpha = 10, n_estimators = 10)
    xg_reg.fit(X_train,y_train)


    y_pred = xg_reg.predict(test)

    # Create file for the competition submission
    test['isBackorder'] = y_pred
    pred = test['isBackorder'].reset_index()
    pred.to_csv('competitionsubmission.csv',index=False)
Run Code Online (Sandbox Code Playgroud)

这是我尝试测量问题准确性的函数(使用 RMSE …

python training-data scikit-learn xgboost k-fold

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