李宏毅老师给的参考代码如下:
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential
from keras.layers.core import Dense,Dropout,Activation
from keras.optimizers import SGD,Adam
import numpy as np
def fizzbuzz(start,end):
x_train,y_train=[],[]
for i in range(start,end+1):
num = i
tmp=[0]*10
j=0
while num :
tmp[j] = num & 1
num = num>>1
j+=1
x_train.append(tmp)
if i % 3 == 0 and i % 5 ==0:
y_train.append([0,0,0,1])
elif i % 3 == 0:
y_train.append([0,1,0,0])
elif i % 5 == 0:
y_train.append([0,0,1,0])
else :
y_train.append([1,0,0,0])
return np.array(x_train),np.array(y_train)
x_train,y_train = fizzbuzz(101,1000) #打标记函数
x_test,y_test = fizzbuzz(1,100)
model = Sequential()
model.add(Dense(input_dim=10,output_dim=100))
model.add(Activation('relu'))
model.add(Dense(output_dim=4))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
model.fit(x_train,y_train,batch_size=20,nb_epoch=100)
result = model.evaluate(x_test,y_test,batch_size=1000)
print('Acc:',result[1])`
运行结果出错:结果如下:
Traceback (most recent call last):
File "C:\Users\19025\Desktop\sublime\练习\sjwl.py", line 84, in <module>
model.add(Dense(input_dim=10,output_dim=100))
TypeError: __init__() missing 1 required positional argument: 'units'
错误是因为:
model.add(Dense(input_dim=10,output_dim=100))
中间缺少units这个量,其实是因为output_dim在新版本中就是units,相应位置程序修改为:
model.add(Dense(input_dim=10,units=100))
model.add(Dense(units=4))
依旧报错,报错信息如下:
Traceback (most recent call last):
File "C:\Users\19025\Desktop\sublime\练习\sjwl.py", line 91, in <module>
model.fit(x_train,y_train,batch_size=20,nb_epoch=100)
File "D:\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 108, in _method_wrapper
return method(self, *args, **kwargs)
TypeError: fit() got an unexpected keyword argument 'nb_epoch'
这是因为新版本nb_epoch改为epochs,
修改相应代码:
model.fit(x_train,y_train,batch_size=20,epochs=100)
运行,成功!
完整程序如下:
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential
from keras.layers.core import Dense,Dropout,Activation
from keras.optimizers import SGD,Adam
import numpy as np
def fizzbuzz(start,end):
x_train,y_train=[],[]
for i in range(start,end+1):
num = i
tmp=[0]*10
j=0
while num :
tmp[j] = num & 1
num = num>>1
j+=1
x_train.append(tmp)
if i % 3 == 0 and i % 5 ==0:
y_train.append([0,0,0,1])
elif i % 3 == 0:
y_train.append([0,1,0,0])
elif i % 5 == 0:
y_train.append([0,0,1,0])
else :
y_train.append([1,0,0,0])
return np.array(x_train),np.array(y_train)
x_train,y_train = fizzbuzz(101,1000) #打标记函数
x_test,y_test = fizzbuzz(1,100)
model = Sequential()
model.add(Dense(input_dim=10,units=100))
model.add(Activation('relu'))
model.add(Dense(units=4))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
model.fit(x_train,y_train,batch_size=20,epochs=100)
result = model.evaluate(x_test,y_test,batch_size=1000)
print('Acc:',result[1])