Unsupported operand type s for int and nonetype как исправить

I don't understand this error OR what it means. I will paste my code underneath, but I don't think it is really relevant; I just want to understand this error. It's just a bit of code to add up the

I don’t understand this error OR what it means. I will paste my code underneath, but I don’t think it is really relevant; I just want to understand this error.

It’s just a bit of code to add up the letters in all numbers 1 — 1000 (inclusive)

def number_translator(x):
    if x == 1:
        return 3
    elif x == 2:
        return 3
    elif x == 3:
        return 5
    elif x == 4:
        return 4
    elif x == 5:
        return 4
    elif x == 6:
        return 3
    elif x == 7:
        return 5
    elif x == 8:
        return 5
    elif x == 9:
        return 4
    elif x == 10:
        return 3
    elif x == 11:
        return 6
    elif x == 12:
        return 6
    elif x == 14:
        return 8
    elif x == 15:
        return 7
    elif x == 16:
        return 7
    elif x == 17:
        return 9
    elif x == 18:
        return 8
    elif x == 19:
        return 8
    elif x == 20:
        return 6
    elif x == 30:
        return 6
    elif x == 40:
        return 5
    elif x == 50:
        return 5
    elif x == 60:
        return 5
    elif x == 70:
        return 7
    elif x == 80:
        return 6
    elif x == 90:
        return 6

count = 0
for element in range(1, 1001):
    if element < 21:
        count += number_translator(element)              # for numbers 1 - 20
    elif 20 < element < 100:
        count += number_translator(int(str(element)[0]) * 10) + number_translator(int(str(element)[1]))  # for numbers 21 through 100
    elif element % 100 == 0 and element != 1000:
        count += number_translator(int(str(element)[0])) + 7   # for numbers divisible by 100, but not 1000
    elif element == 1000:
        count += 11                                          # just for 1000
    elif element % 100 < 20:
        count += number_translator(int(str(element)[0])) + 10 + number_translator(int(str(element)[1:3]))      # now I add in numbers like 101 - 120, 201 - 220, etc.
    else:
        count += number_translator(int(str(element)[0])) + 10 + number_translator(int(str(element)[1]) * 10) + number_translator(int(str(element)[2])) # now the rest( 121, 122, 123, 225, 256, 984, etc.)

print(count)

In python, TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’ error occurs when an integer value is added to a variable that is None. You can add an integer number with a another number. You can’t add a number to None. The Error TypeError: unsupported operand type(s) for +: ‘int’ and ‘NoneType’ will be thrown if an integer value is added with an operand or an object that is None.

An mathematical addition is performed between two numbers. It may be an integer, a float, a long number, etc. The number can not be added to the operand or object that is None. None means that no value is assigned to the variable. So if you try to add a number to a variable that is None, the error TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’ will be thrown.

Objects other than numbers can not be used for arithmetic operations such as addition , subtraction, etc. If you try to add a number to a variable that is None, the error TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’ will be displayed. The None variable should be assigned to an integer before it is added to another number.

Exception

The error TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’ will be shown as below the stack trace. The stack trace shows the line where an integer value is added to a variable that is None.

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x + y
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
[Finished in 0.0s with exit code 1]

How to reproduce this error

If you try to add an integer value with a variable that is not assigned to a value, the error will be reproduced. Create two python variables. Assign a variable that has a valid integer number. Assign another variable to None. Add the two variables to the arithmetic addition operator.

x = None
y = 2
print x + y

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x + y
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
[Finished in 0.0s with exit code 1]

Root Cause

In Python, the arithmetic operation addition can be used to add two valid numbers. If an integer value is added with a variable that is assigned with None, this error TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’ will be thrown. The None variable should be assigned a valid number before it is added to the integer value.

Solution 1

If an integer value is added with a variable that is None, the error will be shown. A valid integer number must be assigned to the unassigned variable before the mathematical addition operation is carried out. This is going to address the error.

x = 3
y = 2
print x + y

Output

5
[Finished in 0.1s]

Solution 2

If the variable is assigned to None, skip to add the variable to the integer. If the variable does not have a value, you can not add it. If the variable type is NoneType, avoid adding the variable to the integer. Otherwise, the output will be unpredictable. If a variable is None, use an alternate flow in the code.

x = None
y = 2
if x is not None :
	print x + y
else :
	print y

Output

2
[Finished in 0.1s]

Solution 3

If the variable is assigned to None, assign the default value to the variable. For eg, if the variable is None, assign the variable to 0. The error will be thrown if the default value is assigned to it. The variable that is None has no meaning at all. You may assign a default value that does not change the value of the expression. In addition, the default value is set to 0. In the case of multiplication, the default value is 1.

x = None
y = 2
if x is None :
	x = 0
print x + y

Output

2
[Finished in 0.1s]

misterJ

0 / 0 / 0

Регистрация: 03.12.2020

Сообщений: 3

1

03.12.2020, 19:09. Показов 10681. Ответов 4

Метки нет (Все метки)


Python
1
2
3
4
5
6
7
def F(n):
    if n > 2:
        return G(n-2)
def G(n):
    if n > 1:
        return F(n - 1) + n
print(F(8))

return F(n — 1) + n
TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’

Как исправить ошибку? Аналогичный код, написанный на Паскале выводит правильный ответ 9

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Автоматизируй это!

Эксперт Python

6481 / 4174 / 1140

Регистрация: 30.03.2015

Сообщений: 12,325

Записей в блоге: 29

03.12.2020, 19:26

2

Цитата
Сообщение от misterJ
Посмотреть сообщение

Как исправить ошибку?

подумать. да, да помню, сейчас все разжую

Цитата
Сообщение от misterJ
Посмотреть сообщение

def F(n):
    if n > 2:
        return G(n-2)

а если n меньше или равно 2? верно, пайтон вернет None

Цитата
Сообщение от misterJ
Посмотреть сообщение

return F(n — 1) + n

здесь вернулся NOne и ты к нему прибавляешь n

Как исправить — или кидать в функцию только больше 2 или написать там и условие что вернуть если меньше или равно 2



0



299 / 181 / 95

Регистрация: 01.05.2014

Сообщений: 504

03.12.2020, 19:28

3

Цитата
Сообщение от misterJ
Посмотреть сообщение

Аналогичный код, написанный на Паскале выводит правильный ответ 9

Хотелось бы взглянуть



0



misterJ

0 / 0 / 0

Регистрация: 03.12.2020

Сообщений: 3

03.12.2020, 19:33

 [ТС]

4

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function G(n: integer):integer; forward;
 
function F(n:integer):integer;
begin
if n > 2 then F:= G(n - 2);
end; 
 
function G(n:integer):integer;
begin
if n > 1 then G:= F(n - 1) + n;
end; 
 
BEGIN
WriteLn(F(8));
END.

Вот код на Паскале вроде работает, выдает 9

Добавлено через 1 минуту
выше прикрепил код



0



Val Rubis

299 / 181 / 95

Регистрация: 01.05.2014

Сообщений: 504

04.12.2020, 16:00

5

Лучший ответ Сообщение было отмечено misterJ как решение

Решение

Так как

Python
1
F(n - 1) + n

возвращает None, добавил

Python
1
else: return 0

Тогда стало считать.
Borland Pascal 7.0 вообще дичь показывает.
Delphi 10.2 получше, но некоторые значения улетают,в третьем десятке небольшой скачок, который к четвертому десятку возвращается к значениям Python.



0



  1. the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' in Python
  2. Fix the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' in Python
  3. Fix the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' Inside a Function

Python TypeError: Unsupported Operand Type(s) for +: 'NoneType' and 'Int'

In Python the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' occurs when you add an integer value with a null value. We’ll discuss in this article the Python error and how to resolve it.

the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' in Python

The Python compiler throws the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' because we are manipulating two values with different datatypes. In this case, the data types of these values are int and null, and the error is educating you that the operation is not supported because the operand int and null for the + operator are invalid.

Code Example:

a = None
b = 32

print("The data type of a is ", type(a))
print("The data type of b is ", type(b))

# TypeError --> unsupported operand type(s) for +: 'NoneType' and 'int'
result = a+b

Output:

The data type of a is  <class 'NoneType'>
The data type of b is  <class 'int'>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

As we see in the output of the above program, the data type of a is NoneType, whereas the data type of b is int. When we try to add the variables a and b, we encounter the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'.

Here are a few similar cases that also cause TypeError because their data types differ.

# Adding a string and an integer
a = "string"
b = 32
a+b         # --> Error

# Adding a Null value and a string
a = None
b = "string"
a+b         # --> Error

# Adding char value and a float
a = 'D'
b = 1.1
a+b         # --> Error

Fix the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' in Python

You cannot use null to perform arithmetic operations on it, and the above program has demonstrated that it throws an error. Furthermore, if you have any similar case, you typecast the values before performing any arithmetic operations or other desired tasks.

To fix this error, you can use valid data types to perform any arithmetic operations on it, typecast the values, or if your function returns null values, you can use try-catch blocks to save your program from crashing.

Code Example:

a = "Delf"
b = "Stack"

print("The data type of a is ", type(a))
print("The data type of b is ", type(b))

result = a+b

print(result)

Output:

The data type of a is  <class 'str'>
The data type of b is  <class 'str'>
DelfStack

As you can see, we have similar data types for a and b, which are perfectly concatenated without throwing any error because the nature of both variables is the same.

Fix the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' Inside a Function

Code Example:

def sum_ab(a, b=None):
        return a+b #TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

sum_ab(3)

Output:

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

In the above code, the sum_ab() function has two arguments, a and b, whereas b is assigned to a null value its the default argument, and the function returns the sum of a and b.

Let’s say you have provided only one parameter, sum_ab(3). The function will automatically trigger the default parameter to None, which cannot be added, as seen in the above examples.

In this case, if you are unsure what function raised the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int', you can use the try-catch mechanism to overcome such errors.

Code Example:

try:
    def sum_ab(a, b=None):
        return a+b

    sum_ab(3)

except TypeError:
    print(" unsupported operand type(s) for +: 'int' and 'NoneType' n The data types are a and b are invalid")

Output:

 unsupported operand type(s) for +: 'int' and 'NoneType'
 The data types are a and b are invalid

The try-catch block helps you interpret the errors and protect your program from crashing.

The difference between data found in many tutorials and data in the real world is that real-world data is rarely clean and homogeneous.
In particular, many interesting datasets will have some amount of data missing.
To make matters even more complicated, different data sources may indicate missing data in different ways.

In this section, we will discuss some general considerations for missing data, discuss how Pandas chooses to represent it, and demonstrate some built-in Pandas tools for handling missing data in Python.
Here and throughout the book, we’ll refer to missing data in general as null, NaN, or NA values.

Trade-Offs in Missing Data Conventions¶

There are a number of schemes that have been developed to indicate the presence of missing data in a table or DataFrame.
Generally, they revolve around one of two strategies: using a mask that globally indicates missing values, or choosing a sentinel value that indicates a missing entry.

In the masking approach, the mask might be an entirely separate Boolean array, or it may involve appropriation of one bit in the data representation to locally indicate the null status of a value.

In the sentinel approach, the sentinel value could be some data-specific convention, such as indicating a missing integer value with -9999 or some rare bit pattern, or it could be a more global convention, such as indicating a missing floating-point value with NaN (Not a Number), a special value which is part of the IEEE floating-point specification.

None of these approaches is without trade-offs: use of a separate mask array requires allocation of an additional Boolean array, which adds overhead in both storage and computation. A sentinel value reduces the range of valid values that can be represented, and may require extra (often non-optimized) logic in CPU and GPU arithmetic. Common special values like NaN are not available for all data types.

As in most cases where no universally optimal choice exists, different languages and systems use different conventions.
For example, the R language uses reserved bit patterns within each data type as sentinel values indicating missing data, while the SciDB system uses an extra byte attached to every cell which indicates a NA state.

Missing Data in Pandas¶

The way in which Pandas handles missing values is constrained by its reliance on the NumPy package, which does not have a built-in notion of NA values for non-floating-point data types.

Pandas could have followed R’s lead in specifying bit patterns for each individual data type to indicate nullness, but this approach turns out to be rather unwieldy.
While R contains four basic data types, NumPy supports far more than this: for example, while R has a single integer type, NumPy supports fourteen basic integer types once you account for available precisions, signedness, and endianness of the encoding.
Reserving a specific bit pattern in all available NumPy types would lead to an unwieldy amount of overhead in special-casing various operations for various types, likely even requiring a new fork of the NumPy package. Further, for the smaller data types (such as 8-bit integers), sacrificing a bit to use as a mask will significantly reduce the range of values it can represent.

NumPy does have support for masked arrays – that is, arrays that have a separate Boolean mask array attached for marking data as «good» or «bad.»
Pandas could have derived from this, but the overhead in both storage, computation, and code maintenance makes that an unattractive choice.

With these constraints in mind, Pandas chose to use sentinels for missing data, and further chose to use two already-existing Python null values: the special floating-point NaN value, and the Python None object.
This choice has some side effects, as we will see, but in practice ends up being a good compromise in most cases of interest.

None: Pythonic missing data¶

The first sentinel value used by Pandas is None, a Python singleton object that is often used for missing data in Python code.
Because it is a Python object, None cannot be used in any arbitrary NumPy/Pandas array, but only in arrays with data type 'object' (i.e., arrays of Python objects):

In [1]:

import numpy as np
import pandas as pd

In [2]:

vals1 = np.array([1, None, 3, 4])
vals1

Out[2]:

array([1, None, 3, 4], dtype=object)

This dtype=object means that the best common type representation NumPy could infer for the contents of the array is that they are Python objects.
While this kind of object array is useful for some purposes, any operations on the data will be done at the Python level, with much more overhead than the typically fast operations seen for arrays with native types:

In [3]:

for dtype in ['object', 'int']:
    print("dtype =", dtype)
    %timeit np.arange(1E6, dtype=dtype).sum()
    print()
dtype = object
10 loops, best of 3: 78.2 ms per loop

dtype = int
100 loops, best of 3: 3.06 ms per loop

The use of Python objects in an array also means that if you perform aggregations like sum() or min() across an array with a None value, you will generally get an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-749fd8ae6030> in <module>()
----> 1 vals1.sum()

/Users/jakevdp/anaconda/lib/python3.5/site-packages/numpy/core/_methods.py in _sum(a, axis, dtype, out, keepdims)
     30 
     31 def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
---> 32     return umr_sum(a, axis, dtype, out, keepdims)
     33 
     34 def _prod(a, axis=None, dtype=None, out=None, keepdims=False):

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

This reflects the fact that addition between an integer and None is undefined.

NaN: Missing numerical data¶

The other missing data representation, NaN (acronym for Not a Number), is different; it is a special floating-point value recognized by all systems that use the standard IEEE floating-point representation:

In [5]:

vals2 = np.array([1, np.nan, 3, 4]) 
vals2.dtype

Notice that NumPy chose a native floating-point type for this array: this means that unlike the object array from before, this array supports fast operations pushed into compiled code.
You should be aware that NaN is a bit like a data virus–it infects any other object it touches.
Regardless of the operation, the result of arithmetic with NaN will be another NaN:

Note that this means that aggregates over the values are well defined (i.e., they don’t result in an error) but not always useful:

In [8]:

vals2.sum(), vals2.min(), vals2.max()

NumPy does provide some special aggregations that will ignore these missing values:

In [9]:

np.nansum(vals2), np.nanmin(vals2), np.nanmax(vals2)

Keep in mind that NaN is specifically a floating-point value; there is no equivalent NaN value for integers, strings, or other types.

NaN and None in Pandas¶

NaN and None both have their place, and Pandas is built to handle the two of them nearly interchangeably, converting between them where appropriate:

In [10]:

pd.Series([1, np.nan, 2, None])

Out[10]:

0    1.0
1    NaN
2    2.0
3    NaN
dtype: float64

For types that don’t have an available sentinel value, Pandas automatically type-casts when NA values are present.
For example, if we set a value in an integer array to np.nan, it will automatically be upcast to a floating-point type to accommodate the NA:

In [11]:

x = pd.Series(range(2), dtype=int)
x

Out[12]:

0    NaN
1    1.0
dtype: float64

Notice that in addition to casting the integer array to floating point, Pandas automatically converts the None to a NaN value.
(Be aware that there is a proposal to add a native integer NA to Pandas in the future; as of this writing, it has not been included).

While this type of magic may feel a bit hackish compared to the more unified approach to NA values in domain-specific languages like R, the Pandas sentinel/casting approach works quite well in practice and in my experience only rarely causes issues.

The following table lists the upcasting conventions in Pandas when NA values are introduced:

Typeclass Conversion When Storing NAs NA Sentinel Value
floating No change np.nan
object No change None or np.nan
integer Cast to float64 np.nan
boolean Cast to object None or np.nan

Keep in mind that in Pandas, string data is always stored with an object dtype.

Operating on Null Values¶

As we have seen, Pandas treats None and NaN as essentially interchangeable for indicating missing or null values.
To facilitate this convention, there are several useful methods for detecting, removing, and replacing null values in Pandas data structures.
They are:

  • isnull(): Generate a boolean mask indicating missing values
  • notnull(): Opposite of isnull()
  • dropna(): Return a filtered version of the data
  • fillna(): Return a copy of the data with missing values filled or imputed

We will conclude this section with a brief exploration and demonstration of these routines.

Detecting null values¶

Pandas data structures have two useful methods for detecting null data: isnull() and notnull().
Either one will return a Boolean mask over the data. For example:

In [13]:

data = pd.Series([1, np.nan, 'hello', None])

Out[14]:

0    False
1     True
2    False
3     True
dtype: bool

Out[15]:

0        1
2    hello
dtype: object

The isnull() and notnull() methods produce similar Boolean results for DataFrames.

Dropping null values¶

In addition to the masking used before, there are the convenience methods, dropna()
(which removes NA values) and fillna() (which fills in NA values). For a Series,
the result is straightforward:

Out[16]:

0        1
2    hello
dtype: object

For a DataFrame, there are more options.
Consider the following DataFrame:

In [17]:

df = pd.DataFrame([[1,      np.nan, 2],
                   [2,      3,      5],
                   [np.nan, 4,      6]])
df

Out[17]:

0 1 2
0 1.0 NaN 2
1 2.0 3.0 5
2 NaN 4.0 6

We cannot drop single values from a DataFrame; we can only drop full rows or full columns.
Depending on the application, you might want one or the other, so dropna() gives a number of options for a DataFrame.

By default, dropna() will drop all rows in which any null value is present:

Alternatively, you can drop NA values along a different axis; axis=1 drops all columns containing a null value:

In [19]:

df.dropna(axis='columns')

But this drops some good data as well; you might rather be interested in dropping rows or columns with all NA values, or a majority of NA values.
This can be specified through the how or thresh parameters, which allow fine control of the number of nulls to allow through.

The default is how='any', such that any row or column (depending on the axis keyword) containing a null value will be dropped.
You can also specify how='all', which will only drop rows/columns that are all null values:

Out[20]:

0 1 2 3
0 1.0 NaN 2 NaN
1 2.0 3.0 5 NaN
2 NaN 4.0 6 NaN

In [21]:

df.dropna(axis='columns', how='all')

Out[21]:

0 1 2
0 1.0 NaN 2
1 2.0 3.0 5
2 NaN 4.0 6

For finer-grained control, the thresh parameter lets you specify a minimum number of non-null values for the row/column to be kept:

In [22]:

df.dropna(axis='rows', thresh=3)

Here the first and last row have been dropped, because they contain only two non-null values.

Filling null values¶

Sometimes rather than dropping NA values, you’d rather replace them with a valid value.
This value might be a single number like zero, or it might be some sort of imputation or interpolation from the good values.
You could do this in-place using the isnull() method as a mask, but because it is such a common operation Pandas provides the fillna() method, which returns a copy of the array with the null values replaced.

Consider the following Series:

In [23]:

data = pd.Series([1, np.nan, 2, None, 3], index=list('abcde'))
data

Out[23]:

a    1.0
b    NaN
c    2.0
d    NaN
e    3.0
dtype: float64

We can fill NA entries with a single value, such as zero:

Out[24]:

a    1.0
b    0.0
c    2.0
d    0.0
e    3.0
dtype: float64

We can specify a forward-fill to propagate the previous value forward:

In [25]:

# forward-fill
data.fillna(method='ffill')

Out[25]:

a    1.0
b    1.0
c    2.0
d    2.0
e    3.0
dtype: float64

Or we can specify a back-fill to propagate the next values backward:

In [26]:

# back-fill
data.fillna(method='bfill')

Out[26]:

a    1.0
b    2.0
c    2.0
d    3.0
e    3.0
dtype: float64

For DataFrames, the options are similar, but we can also specify an axis along which the fills take place:

Out[27]:

0 1 2 3
0 1.0 NaN 2 NaN
1 2.0 3.0 5 NaN
2 NaN 4.0 6 NaN

In [28]:

df.fillna(method='ffill', axis=1)

Out[28]:

0 1 2 3
0 1.0 1.0 2.0 2.0
1 2.0 3.0 5.0 5.0
2 NaN 4.0 6.0 6.0

Notice that if a previous value is not available during a forward fill, the NA value remains.

hi there
I am new to eras, and learning about it, for my fist model I am trying create a CNN 1D and every time I try to compile this I am getting the same error I try with even and Odds parameters,

here is the errors and bellow is the source code of my model. could some one please point me out my error and some resource for the solution?
thanks a lot
angelo

Traceback (most recent call last):
File «character_cnn.py», line 206, in
model.add(Dense(hidden_dims))
File «/usr/local/lib/python2.7/dist-packages/keras/layers/containers.py», line 32, in add
self.layers[-1].set_previous(self.layers[-2])
File «/usr/local/lib/python2.7/dist-packages/keras/layers/core.py», line 34, in set_previous
assert self.input_ndim == len(layer.output_shape), «Incompatible shapes: layer expected input with ndim=» +
File «/usr/local/lib/python2.7/dist-packages/keras/layers/core.py», line 588, in output_shape
return (input_shape[0], np.prod(input_shape[1:]))
File «/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py», line 2481, in prod
out=out, keepdims=keepdims)
File «/usr/local/lib/python2.7/dist-packages/numpy/core/_methods.py», line 35, in _prod
return umr_prod(a, axis, dtype, out, keepdims)
TypeError: unsupported operand type(s) for *: ‘NoneType’ and ‘int’

nb_samples = X_train.shape[0]
nb_features = X_train.shape[1]
newshape = (nb_samples, 1, nb_features, 1)
X_train = np.reshape(X_train, newshape).astype(np.int)

We set some hyperparameters

BATCH_SIZE = 16
maxlen = 10
max_features = a.shape[1]
FIELD_SIZE = 5 * 300
STRIDE = 300
N_FILTERS = a.shape[1]
nb_classes =22
embedding_dims = 50
nb_filters = 250
filter_length = 2

number of hidden nodes in full connected layer

hidden_dims = 250

print(‘Build model…’)
model = Sequential()

model.add(Embedding(max_features, embedding_dims))
model.add(Dropout(0.25))
print «embedding dims: «, embedding_dims

we add a Convolution1D, which will learn nb_filter

word group filters of size filter_length:

model.add(Convolution1D(input_dim=embedding_dims,
nb_filter=nb_filters,
filter_length=filter_length,
border_mode=»valid»,
activation=»relu»,
subsample_length=1))
model.add(Activation(‘relu’))

we use standard max pooling (halving the output of the previous layer):

model.add(MaxPooling1D(pool_length=2))

We flatten the output of the conv layer,

so that we can add a vanilla dense layer:

model.add(Flatten())

Computing the output shape of a conv layer can be tricky;

for a good tutorial, see: http://cs231n.github.io/convolutional-networks/

output_size = nb_filters * (((maxlen — filter_length) / 1) + 1) / 2
print output_size
print nb_filters

I get the error in here no matter any parameter that I change

model.add(Dense(hidden_dims))
model.add(Dropout(0.25))
model.add(Activation(‘relu’))

model.add(Dense(nb_classes))

We project onto a single unit output layer, and squash it with a sigmoid:

model.add(Activation(‘softmax’))

model.compile(loss=’categorical_crossentropy’,
optimizer=’adadelta’)
print «fitting model»
model.fit(X_train, y_train, batch_size=BATCH_SIZE, verbose=1,
nb_epoch=10, show_accuracy=True,
validation_split=0.1)
score = model.evaluate(X_test, Y_test, show_accuracy=True, verbose=0)
print(‘Test score:’, score[0])
print(‘Test accuracy:’, score[1])

Понравилась статья? Поделить с друзьями:
  • Unrecognized option xincgc error could not create the java virtual machine
  • Unsupported graphics card epic games как исправить windows 10
  • Unsupported gpu processing mode davinci как исправить
  • Unsupported file на телевизоре как исправить
  • Unsupported file на проекторе как исправить