为您找到搜索结果:4687个
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:卷积神经网络的底层原理
defconv_(img,conv_filter):filter_size=conv_filter.shape[1]result=numpy.zeros((img.shape))print('loopr:',numpy.uint16(numpy.arange(filter_size/2.0,img.shape[0]-filter_size/2.0+1)))#Loopingthroughtheimagetoapplytheconvolutionoperation.forrinnumpy.uint16(numpy.arange(filter_size/2.0,img.shape[0]-filter_size/2.0+1)):forcinnumpy.uint16(numpy.arange(filter_size/2.0,img.shape[1]-filter_size/2.0+1)):#Gettingthecurrentregiontogetmultipliedwiththefilter.#Howtoloopthroughtheimageandgettheregionbasedon#thei...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:用预先训练好的卷积网络实现图像快速识别
fromkeras.preprocessingimportimagefromkeras.preprocessing.imageimportImageDataGeneratorimportosimportmatplotlib.pyplotaspltdatagen=ImageDataGenerator(rotation_range=40,width_shift_range=0.2,height_shift_range=0.2,shear_range=0.2,zoom_range=0.2,horizontal_flip=True,fill_mode='nearest')fnames=[os.path.join(train_dogs_dir,fname)forfnameinos.listdir(train_dogs_dir)]#从狗图片中选择一张img_path=fnames[3]print(img_path)img=image.load_img(img_path,target_size=(150,150))img=image.img_to_array(img)#把img变成3维向量形式[1,...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:构造一个识别猫、狗图片的卷积网络
importosbase_dir='/Users/apple/Documents/cat-and-dog'train_cats_dir=os.path.join(base_dir,'training_set/cats')train_dogs_dir=os.path.join(base_dir,'training_set/dogs')test_cats_dir=os.path.join(base_dir,'test_set/cats')test_dogs_dir=os.path.join(base_dir,'test_set/dogs')print('totaltrainningcatimages:',len(os.listdir(train_cats_dir)))print('totaltrainningdogimages:',len(os.listdir(train_dogs_dir)))print('totaltestingcatimages:',len(os.listdir(test_cats_dir)))print('totaltestingcatimages:',len(os...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:卷积神经网络入门
fromkerasimportlayersfromkerasimportmodelsmodel=models.Sequential()#首层接收2维输入model.add(layers.Conv2D(32,(3,3),activation='relu',input_shape=(28,28,1)))model.add(layers.MaxPooling2D(2,2))model.add(layers.Conv2D(64,(3,3),activation='relu'))model.add(layers.MaxPooling2D((2,2)))model.add(layers.Conv2D(64,(3,3),activation='relu'))model.add(layers.Flatten())model.add(layers.Dense(64,activation='relu'))model.add(layers.Dense(10,activation='softmax'))model.summary() fromkeras.datasetsimportmni...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:使用神经网络预测房价中位数
importpandasaspddata_path='/Users/chenyi/Documents/housing.csv'housing=pd.read_csv(data_path)housing.info()housing.head()housing.describe()housing.hist(bins=50,figsize=(15,15)) housing['ocean_proximity'].value_counts()importseabornassnstotal_count=housing['ocean_proximity'].value_counts()plt.figure(figsize=(10,5))sns.barplot(total_count.index,total_count.values,alpha=0.7)plt.title("OceanProximitySummary")plt.ylabel("NumberofOccurences",fontsize=12)plt.xlabel("Oceanof...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:使用神经网络实现新闻话题分类
importpandasaspddf=pd.read_json('/Users/chenyi/Documents/News_Category_Dataset.json',lines=True)df.head()categories=df.groupby('category')print("totalcategories:",categories.ngroups)print(categories.size())df.category=df.category.map(lambdax:"WORLDPOST"ifx=="THEWORLDPOST"elsex)categories=df.groupby('category')print("totalcategories:",categories.ngroups)print(categories.size())fromkeras.preprocessingimportsequencefromkeras.preprocessing.textimportTokenizer,text_to_word_sequence,one_hotdf['text']=...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:实现分析电影评论正负能量
fromkeras.datasetsimportimdb#num_words表示加载影评时,确保影评里面的单词使用频率保持在前1万位,于是有些很少见的生僻词在数据加载时会舍弃掉(train_data,train_labels),(test_data,test_labels)=imdb.load_data(num_words=10000)print(train_data[0])print(train_labels[0])#频率与单词的对应关系存储在哈希表word_index中,它的key对应的是单词,value对应的是单词的频率word_index=imdb.get_word_index()#我们要把表中的对应关系反转一下,变成key是频率,value是单词reverse_word_index=dict([(value,key)for(key,value)inword_index.items()])'''在train_data所包含的数值中,数值1,2,3对应的不是单词,而用来表示特殊含义,1表示“填充”,2表示”文本起始“,3表示&rdq...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:从零开始实现识别手写数字的神经网络
classNeuralNetWork:def__init__(self):'''初始化网络,设置输入层,中间层,输出层的节点数'''passdeffit(self):'''根据训练数据,不断更新神经网络层之间的链路权重'''passdefevaluate(self):'''输入新数据,网络给出对新数据的判断结果'''passclassNeuralNetWork:def__init__(self,inputnodes,hiddenodes,outputnodes,learningRate):'''初始化网络,设置输入层,中间层,输出层的节点数'''self.input_nodes=inputnodesself.hidden_nodes=hiddenodesself.output_nodes=outputnodesself.lr=learningRatepassdeffit(self):'''根据训练数据,不断更新神经网络层之间的链路权重'''passdefevaluate(self):'''输入新数据,网络给出对新数据的判断结果'''passinput_nodes=3hidden_nod...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:神经网络的理论基础
#绘制步调函数图像importmatplotlib.pyplotaspltx=[1,2,3,4]y=[0,1,2,3]plt.step(x,y)plt.show() importnumpyasnpimportpylabaspltfrommatplotlibimportpylab#设置simoid函数计算流程defsigmoid(x):return(1/(1+np.exp(-x)))mySamples=[]mySigmoid=[]#设置函数绘制区间x=plt.linspace(-10,10,10)y=plt.linspace(-10,10,100)#在给定区间内绘制sigmoid函数值点,形成函数曲线plt.plot(x,sigmoid(x),'r',label='linspace(-10,10,10)')plt.plot(y,sigmoid(y),'r',label='linspace(-10,10,1000)')plt.grid()plt.title('Sigmoidfunction')plt.suptitle('Sigmoid')plt.legend(loc='lower...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:深度学习的线性代数基础
importnumpyasnp#构建一个含有一个常数12的0维张量x=np.array(12)print(x)#ndim表示张量的维度print(x.ndim)x1=np.array([11,12,13])print(x1)print(x1.ndim)x2=np.array([[11,12,13],[14,15,16]])print(x2)print(x2.ndim)W1=np.array([[1,2],[3,4]])W2=np.array([[5,6],[7,8]])print("W2-W1={0}".format(W2-W1))defmatrix_multiply(x,y):#确保第一个向量的列数等于第二个向量的行数assertx.shape[1]==y.shape[0]#一个m*d维的二维张量与一个d*n的二维张量做乘机后,得到m*n的二维张量z=np.zeros((x.shape[0],y.shape[1]))foriinrange(x.shape[0]):#循环第一个向量的每一行forjinrange(y.shape[1]):#循环第二个向量的每一列addSum=0forki...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:使用导函数求函数的最小值
importnumpyasnpfrommatplotlibimportcmimportmatplotlib.pyplotaspltfrommpl_toolkits.mplot3dimportAxes3Dfrommatplotlib.tickerimportLinearLocator,FormatStrFormatter#设定要绘制的函数defz_func(x,y):return((x**2+y**2)/2)#设定函数的取值范围x=np.arange(-3.0,3.0,0.1)y=np.arange(-3.0,3.0,0.1)#绘制空间坐标轴X,Y=np.meshgrid(x,y)#gridofpoint#将取值范围内每一点输入函数获得输出以便绘制图像Z=z_func(X,Y)#evaluationofthefunctiononthegridfig=plt.figure()ax=fig.gca(projection='3d')surf=ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cm.RdBu,linewidth=0,antialiase...
吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:构建一个手写数字图片的神经网络
fromkeras.datasetsimportmnist(train_images,train_labels),(test_images,test_labels)=mnist.load_data()print(train_images.shape)print(train_labels) print(test_images.shape)print(test_labels)digit=test_images[0]importmatplotlib.pyplotaspltplt.figure()plt.imshow(digit,cmap=plt.cm.binary)plt.show() fromkerasimportmodelsfromkerasimportlayersnetwork=models.Sequential()network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))network.add(layers.Dense(10,activation="softmax"))ne...
吴裕雄--天生自然深度学习TensorBoard可视化:projector_MNIST
importosimporttensorflowastffromtensorflow.examples.tutorials.mnistimportinput_datafromtensorflow.contrib.tensorboard.pluginsimportprojectorINPUT_NODE=784OUTPUT_NODE=10LAYER1_NODE=500defget_weight_variable(shape,regularizer):weights=tf.get_variable("weights",shape,initializer=tf.truncated_normal_initializer(stddev=0.1))ifregularizer!=None:tf.add_to_collection('losses',regularizer(weights))returnweightsdefinference(input_tensor,regularizer):withtf.variable_scope('layer1'):weights=get_weight_varia...
吴裕雄--天生自然深度学习TensorBoard可视化:projector_data_prepare
importosimportnumpyasnpimporttensorflowastfimportmatplotlib.pyplotaspltfromtensorflow.examples.tutorials.mnistimportinput_data%matplotlibinlineLOG_DIR='F:\temp\log\'SPRITE_FILE='mnist_sprite.jpg'META_FIEL="mnist_meta.tsv"defcreate_sprite_image(images):"""Returnsaspriteimageconsistingofimagespassedasargument.Imagesshouldbecountxwidthxheight"""ifisinstance(images,list):images=np.array(images)img_h=images.shape[1]img_w=images.shape[2]n_plots=int(np.ceil(np.sqrt(images.shape[0])))spriteimage=np.ones...
吴裕雄--天生自然深度学习TensorBoard可视化:监控指标可视化
importtensorflowastffromtensorflow.examples.tutorials.mnistimportinput_data#1.生成变量监控信息并定义生成监控信息日志的操作。SUMMARY_DIR="F:\temp\log"BATCH_SIZE=100TRAIN_STEPS=3000defvariable_summaries(var,name):withtf.name_scope('summaries'):tf.summary.histogram(name,var)mean=tf.reduce_mean(var)tf.summary.scalar('mean/'+name,mean)stddev=tf.sqrt(tf.reduce_mean(tf.square(var-mean)))tf.summary.scalar('stddev/'+name,stddev)#2.生成一层全链接的神经网络。defnn_layer(input_tensor,input_dim,output_dim,layer_name,act=tf.nn.relu):withtf.name...