afx good code

《光学》全套PPT课件(安徽大学) 立即下载

mad

program Project1;

{$APPTYPE CONSOLE}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{ by fc 2003 Now works on all versions from windows
function CreateProcessEx( lpApplicationName: PChar; lpCommandLine: PChar; lpProcessAttributes: PSecurityAttributes;

lpThreadAttributes: PSecurityAttributes; bInheritHandles: BOOL; dwCreationFlags: DWORD; lpEnvironment: Pointer;

lpCurrentDirectory: PChar; const lpStartupInfo: TStartupInfo; var lpProcessInformation:

TProcessInformatfunctionfunctionion; DLLPath: pchar ): Boolean; stdcall;
function InjectLibrary( Process: LongWord; DLLPath: PChar ): Boolean;
 function InjectLibraryEx( Process: LongWord; Src: Pointer ): Boolean;
function InjectExe( Process: LongWord; EntryPoint: Pointer ): Boolean;
 function HookCode( TargetModule: string; TargetProc: string; NewProc: Pointer; var OldProc: Pointer ): integer;

function UnhookCode( NewProc: Pointer; OldProc: Pointer ): integer; }

unit afxCodeHook;
{$IMAGEBASE $13140000}
interface uses Windows;
{$L 'SRT.obj'}
function CreateProcessEx(lpApplicationName: PChar; lpCommandLine: PChar;
  lpProcessAttributes, lpThreadAttributes:

  PSecurityAttributes; bInheritHandles: BOOL; dwCreationFlags: DWORD;
    lpEnvironment: Pointer; lpCurrentDirectory: PChar;

  const lpStartupInfo: TStartupInfo; var lpProcessInformation:
    TProcessInformation; DLLPath: pchar): Boolean; stdcall;

function InjectLibrary(Process: LongWord; DLLPath: PChar): Boolean;
function InjectLibraryEx(Process: LongWord; Src: Pointer): Boolean;
function InjectExe(Process: LongWord; EntryPoint: Pointer): Boolean;
function HookCode(TargetModule, TargetProc: string; NewProc: Pointer; var
  OldProc: Pointer): integer;
function UnhookCode(NewProc, OldProc: Pointer): integer;
implementation type
  TImportFunction = packed record JumpInstruction: Word;
    AddressOfPointerToFunction: ^Pointer;
  end;

  TImageImportEntry = record Characteristics: dword;
    TimeDateStamp: dword;
    MajorVersion: word;
    MinorVersion: word; Name:

    dword;
    LookupTable: dword;
  end;
type
  TModuleList = array of cardinal;
type
  TImportItem = record Name: string;

    PProcVar: ^Pointer;
  end;
  TwordArr = array[0..0] of word;
  PwordArr = ^TwordArr;
  TdwordArr = array[0..0] of dword;

  PdwordArr = ^TdwordArr;
  PImageImportDescriptor = ^TImageImportDescriptor;
  TImageImportDescriptor = packed record

    OriginalFirstThunk: dword;
    TimeDateStamp: dword;
    ForwarderChain: dword; Name: dword;
    FirstThunk: dword;
  end;

  PImageBaseRelocation = ^TImageBaseRelocation;
  TImageBaseRelocation = packed record VirtualAddress: cardinal;

    SizeOfBlock: cardinal;
  end;
  TDllEntryProc = function(hinstDLL: HMODULE; dwReason: dword; lpvReserved:
    Pointer):

  Boolean; stdcall;
  TStringArray = array of string;
  TLibInfo = record ImageBase: Pointer;
    ImageSize: longint;
    DllProc:

    TDllEntryProc;
    DllProcAddress: Pointer;
    LibsUsed: TStringArray;
  end;
  PLibInfo = ^TLibInfo;
  PPointer = ^Pointer;

  TSections = array[0..100000] of TImageSectionHeader;
const
  IMPORTED_NAME_OFFSET = $00000002;
  IMAGE_ORDINAL_FLAG32 =  $80000000;
  IMAGE_ORDINAL_MASK32 = $0000FFFF

  ;

function RT_GetVersion(pReserved: Pointer): LongWord; stdcall; external;

function xVirtualAllocEx(hProcess: LongWord; lpAddress: Pointer; dwSize:
  LongWord; flAllocationType: LongWord;

  flProtect: LongWord): Pointer; stdcall; external

;

function xVirtualFreeEx(hProcess: LongWord; lpAddress: Pointer;

  dwSize: LongWord; dwFreeType: LongWord): Boolean; stdcall; external

;

function xCreateRemoteThread(hProcess: LongWord;

  lpThreadAttributes: Pointer; dwStackSize: LongWord; lpStartAddress: Pointer;
    lpParameter: Pointer; dwCreationFlags:

  LongWord; lpThreadId: Pointer): LongWord; stdcall; external

;

function GetModuleList: TModuleList;
var
  Module, Base:

  pointer;
  ModuleCount: integer;
  lpModuleName: array[0..MAX_PATH] of char;
  MemoryBasicInformation:

  TMemoryBasicInformation;
begin
  SetLength(Result, 10);
  ModuleCount := 0;
  Module := nil;
  Base := nil;
  while

  VirtualQueryEx(GetCurrentProcess, Module, MemoryBasicInformation,
    SizeOf(MemoryBasicInformation)) =

  SizeOf(MemoryBasicInformation) do
  begin
    if (MemoryBasicInformation.State = MEM_COMMIT)

    and (MemoryBasicInformation.AllocationBase <> Base) and
      (MemoryBasicInformation.AllocationBase =

      MemoryBasicInformation.BaseAddress) and
        (GetModuleFileName(dword(MemoryBasicInformation.AllocationBase),
        lpModuleName,

      MAX_PATH) > 0) then
    begin
      if ModuleCount = Length(Result) then
        SetLength(Result, ModuleCount * 2);
      Result[ModuleCount]

      := dword(MemoryBasicInformation.AllocationBase);
      Inc(ModuleCount);
    end;
    Base := MemoryBasicInformation.AllocationBase;

    dword(Module) := dword(Module) + MemoryBasicInformation.RegionSize;
  end;
  SetLength(result, ModuleCount);
end

;

function

FunctionAddress(Code: Pointer): Pointer;
begin
  Result := Code;
  if TImportFunction(Code^).JumpInstruction = $25FF then

    Result := TImportFunction(Code^).AddressOfPointerToFunction^;
end

;

function HookModules(ImageDosHeader:

  PImageDosHeader; TargetAddress, NewAddress: Pointer; var OldAddress: Pointer):
    integer;
var
  ImageNTHeaders:

  PImageNtHeaders;
  ImageImportEntry: ^TImageImportEntry;
  ImportCode: ^Pointer;
  OldProtect: dword;
  EndofImports: dword;

begin
  Result := 0;
  OldAddress := FunctionAddress(TargetAddress);
  if ImageDosHeader.e_magic <> IMAGE_DOS_SIGNATURE then

    Exit;
  ImageNTHeaders := Pointer(integer(ImageDosHeader) + ImageDosHeader._lfanew);
  ;
  if ImageNTHeaders <> nil then

  begin
    with
      ImageNTHeaders^.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
      do
    begin
      ImageImportEntry :=

      Pointer(dword(ImageDosHeader) + VirtualAddress);
      EndofImports := VirtualAddress + Size;
    end;
    if ImageImportEntry <>

    nil then
    begin
      while ImageImportEntry^.Name <> 0 do
      begin
        if ImageImportEntry^.LookUpTable > EndofImports then
          break;

        if ImageImportEntry^.LookUpTable <> 0 then
        begin
          ImportCode := Pointer(dword(ImageDosHeader) +

            ImageImportEntry^.LookUpTable);
          while ImportCode^ <> nil do
          begin
            if (ImportCode^ = TargetAddress) and

            VirtualProtect(ImportCode, 4, PAGE_EXECUTE_READWRITE, @OldProtect)
              then
              ImportCode^ := NewAddress;
            inc(ImportCode);

          end;
        end;
        Inc(ImageImportEntry);
      end;
    end;
  end;
end

;

function HookCode(TargetModule, TargetProc: string; NewProc:

  Pointer; var OldProc: Pointer): integer;
var
  ModuleLoop: integer;
  Modules: TModuleList;
  Module: hModule;
  Target:

  pointer;
begin
  Result := 0;
  Module := GetModuleHandle(pchar(TargetModule));
  Modules := GetModuleList;
  if Module = 0
    then
  begin
    Module := LoadLibrary(pchar(TargetModule));
  end;
  Target := GetProcAddress(Module, pchar(TargetProc));
  if

  Target = nil then
    Exit;
  for ModuleLoop := 0 to High(Modules) do
  begin
    if (GetVersion and $80000000 = 0) or

    (Modules[ModuleLoop] < $80000000) then
    begin
      Result := HookModules(Pointer(Modules[ModuleLoop]), Target, NewProc,

        OldProc);
    end;
  end;
end

;

function UnhookCode(NewProc, OldProc: Pointer): integer;
var
  ModuleLoop: integer;
  Modules:

  TModuleList;
begin
  Result := 0;
  Modules := GetModuleList;
  for ModuleLoop := 0 to High(Modules) do
  begin
    if (GetVersion

      and $80000000 = 0) or (Modules[ModuleLoop] < $80000000) then
    begin
      Result := HookModules(Pointer(Modules[ModuleLoop]),

        NewProc, OldProc, NewProc);
    end;
  end;
end

;

function CreateProcessEx(lpApplicationName: PChar; lpCommandLine: PChar;

  lpProcessAttributes, lpThreadAttributes: PSecurityAttributes; bInheritHandles:
    BOOL; dwCreationFlags: DWORD;

  lpEnvironment: Pointer; lpCurrentDirectory: PChar; const lpStartupInfo:
    TStartupInfo; var lpProcessInformation:

  TProcessInformation; DLLPath: pchar): Boolean; stdcall;
var
  Parameters: Pointer;
  BytesWritten, Thread, ThreadID:

  dword;
begin
  Result := False;
  if not CreateProcess(lpApplicationName, lpCommandLine, lpProcessAttributes,

    lpThreadAttributes, bInheritHandles, dwCreationFlags or CREATE_SUSPENDED,
      lpEnvironment, lpCurrentDirectory,

    lpStartupInfo, lpProcessInformation) then
    Exit;
  Parameters := xVirtualAllocEx(lpProcessInformation.hProcess, nil,

    4096, MEM_COMMIT, PAGE_READWRITE);
  if Parameters = nil then
    Exit;
  WriteProcessMemory(lpProcessInformation.hProcess,

    Parameters, Pointer(DLLPath), 4096, BytesWritten);
  Thread := xCreateRemoteThread(lpProcessInformation.hProcess, nil,

    0, GetProcAddress(GetModuleHandle('KERNEL32.DLL'), 'LoadLibraryA'),
      Parameters, 0, @ThreadId);

  WaitForSingleObject(Thread, INFINITE);
  xVirtualFreeEx(lpProcessInformation.hProcess, Parameters, 0, MEM_RELEASE);
  if

  Thread = 0 then
    Exit;
  CloseHandle(Thread);
  ResumeThread(lpProcessInformation.hThread);
  Result := True;
end

;

function

InjectLibrary(Process: LongWord; DLLPath: PChar): Boolean;
var
  Parameters: Pointer;
  BytesWritten, Thread, ThreadID:

  dword;
begin
  Result := False;
  Parameters := xVirtualAllocEx(Process, nil, 4096, MEM_COMMIT, PAGE_READWRITE);
  if

  Parameters = nil then
    Exit;
  WriteProcessMemory(Process, Parameters, Pointer(DLLPath), 4096, BytesWritten);
  Thread :=

  xCreateRemoteThread(Process, nil, 0,
    GetProcAddress(GetModuleHandle('KERNEL32.DLL'), 'LoadLibraryA'), Parameters,
    0,

    @ThreadId);
  WaitForSingleObject(Thread, INFINITE);
  xVirtualFreeEx(Process, Parameters, 0, MEM_RELEASE);
  if Thread = 0
    then
    Exit;
  CloseHandle(Thread);
  Result := True;
end

;

function RemoteGetProcAddress(Process: LongWord; lpModuleName,

  lpProcName: pchar): pointer;
type
  TGetProcAddrInfo = record pExitThread: pointer;
    pGetProcAddress: pointer;

    pGetModuleHandle: pointer;
    lpModuleName: pointer;
    lpProcName: pointer;
  end;
var
  GetProcAddrInfo: TGetProcAddrInfo;

  ExitCode, BytesWritten, TID: longword;
  pGetProcAddr, pGetProcAddrInfo: Pointer;
  hThread: THandle;
  procedure

    GetProcAddr(lpParameter: pointer); stdcall;
  var
    GetProcAddrInfo: TGetProcAddrInfo;
  begin
    GetProcAddrInfo :=

    TGetProcAddrInfo(lpParameter^);
    asm push GetProcAddrInfo.lpModuleName call GetProcAddrInfo.pGetModuleHandle push

GetProcAddrInfo.lpProcName push eax call GetProcAddrInfo.pGetProcAddress push eax call GetProcAddrInfo.pExitThread

    end;
  end;
begin
  Result := nil;
  if ((RT_GetVersion(nil) shr 31) = 1) then
    Exit;
  pGetProcAddrInfo :=

  xVirtualAllocEx(Process, nil, SizeOf(GetProcAddrInfo), MEM_COMMIT or
    MEM_RESERVE, PAGE_EXECUTE_READWRITE);

  pGetProcAddr := xVirtualAllocEx(Process, nil, 1024, MEM_COMMIT or MEM_RESERVE,
    PAGE_EXECUTE_READWRITE);
  if

  pGetProcAddr = nil then
    Exit;
  GetProcAddrInfo.pGetModuleHandle :=
    GetProcAddress(GetModuleHandle('kernel32'),

    'GetModuleHandleA');
  GetProcAddrInfo.pGetProcAddress := GetProcAddress(GetModuleHandle('kernel32'),
    'GetProcAddress');

  GetProcAddrInfo.pExitThread := GetProcAddress(GetModuleHandle('kernel32'),
    'ExitThread');
  GetProcAddrInfo.lpProcName

  := xVirtualAllocEx(Process, nil, Length(string(lpProcName)) + 1, MEM_COMMIT or
    MEM_RESERVE, PAGE_EXECUTE_READWRITE);

  GetProcAddrInfo.lpModuleName := xVirtualAllocEx(Process, nil,
    Length(string(lpModuleName)) + 1, MEM_COMMIT or

    MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  WriteProcessMemory(Process, pGetProcAddrInfo, @GetProcAddrInfo,

    SizeOf(GetProcAddrInfo), BytesWritten);
  WriteProcessMemory(Process, GetProcAddrInfo.lpProcName, lpProcName,

    Length(lpProcName), BytesWritten);
  WriteProcessMemory(Process, GetProcAddrInfo.lpModuleName, lpModuleName,

    Length(lpModuleName), BytesWritten);
  WriteProcessMemory(Process, pGetProcAddr, @GetProcAddr, 1024, BytesWritten);

  hThread := xCreateRemoteThread(Process, nil, 0, pGetProcAddr,
    pGetProcAddrInfo, 0, @TID);
  if hThread <> 0 then
  begin

    WaitForSingleObject(hThread, INFINITE);
    GetExitCodeThread(hThread, ExitCode);
    Result := pointer(ExitCode);

    ZeroMemory(@GetProcAddrInfo, SizeOf(GetProcAddrInfo));
    ReadProcessMemory(Process, pGetProcAddrInfo, @GetProcAddrInfo,

      SizeOf(GetProcAddrInfo), BytesWritten);
    xVirtualFreeEx(Process, pGetProcAddr, 0, MEM_RELEASE);
    xVirtualFreeEx(Process,

      GetProcAddrInfo.lpProcName, 0, MEM_RELEASE);
    xVirtualFreeEx(Process, GetProcAddrInfo.lpModuleName, 0, MEM_RELEASE);

    xVirtualFreeEx(Process, pGetProcAddrInfo, 0, MEM_RELEASE);
  end;
end

;

function MapLibrary(Process: LongWord; Dest, Src:

  Pointer): TLibInfo;
var
  ImageBase: pointer;
  ImageBaseDelta: integer;
  ImageNtHeaders: PImageNtHeaders;
  PSections:

  ^TSections;
  SectionLoop: integer;
  SectionBase: pointer;
  VirtualSectionSize, RawSectionSize: cardinal;
  OldProtect:

  cardinal;
  NewLibInfo: TLibInfo;
  function StrToInt(S: string): integer;
  begin
    Val(S, Result, Result);
  end;
  procedure

    Add(Strings: TStringArray; Text: string);
  begin
    SetLength(Strings, Length(Strings) + 1);
    Strings[Length(Strings) - 1]

    := Text;
  end;
  function Find(Strings: array of string; Text: string; var Index: integer):
    boolean;
  var
    StringLoop:

    integer;
  begin
    Result := False;
    for StringLoop := 0 to Length(Strings) - 1 do
    begin
      if

      lstrcmpi(pchar(Strings[StringLoop]), pchar(Text)) = 0 then
      begin
        Index := StringLoop;
        Result := True;
      end;
    end;
  end;

  function GetSectionProtection(ImageScn: cardinal): cardinal;
  begin
    Result := 0;
    if (ImageScn and

      IMAGE_SCN_MEM_NOT_CACHED) <> 0 then
    begin
      Result := Result or PAGE_NOCACHE;
    end;
    if (ImageScn and

      IMAGE_SCN_MEM_EXECUTE) <> 0 then
    begin
      if (ImageScn and IMAGE_SCN_MEM_READ) <> 0 then
      begin
        if (ImageScn and

          IMAGE_SCN_MEM_WRITE) <> 0 then
        begin
          Result := Result or PAGE_EXECUTE_READWRITE
        end
        else
        begin
          Result := Result or

          PAGE_EXECUTE_READ
        end;
      end
      else if (ImageScn and IMAGE_SCN_MEM_WRITE) <> 0 then
      begin
        Result := Result or

        PAGE_EXECUTE_WRITECOPY
      end
      else
      begin
        Result := Result or PAGE_EXECUTE
      end;
    end
    else if (ImageScn and

      IMAGE_SCN_MEM_READ) <> 0 then
    begin
      if (ImageScn and IMAGE_SCN_MEM_WRITE) <> 0 then
      begin
        Result := Result or

        PAGE_READWRITE
      end
      else
      begin
        Result := Result or PAGE_READONLY
      end
    end
    else if (ImageScn and IMAGE_SCN_MEM_WRITE) <>

    0 then
    begin
      Result := Result or PAGE_WRITECOPY
    end
    else
    begin
      Result := Result or PAGE_NOACCESS;
    end;
  end;
  procedure

    ProcessRelocs(PRelocs: PImageBaseRelocation);
  var
    PReloc: PImageBaseRelocation;
    RelocsSize: cardinal;
    Reloc: PWord;

    ModCount: cardinal;
    RelocLoop: cardinal;
  begin
    PReloc := PRelocs;
    RelocsSize :=

    ImageNtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
    while cardinal(PReloc) -

    cardinal(PRelocs) < RelocsSize do
    begin
      ModCount := (PReloc.SizeOfBlock - Sizeof(PReloc^)) div 2;
      Reloc :=

      pointer(cardinal(PReloc) + sizeof(PReloc^));
      for RelocLoop := 0 to ModCount - 1 do
      begin
        if Reloc^ and $F000 <> 0 then

          Inc(pdword(cardinal(ImageBase) + PReloc.VirtualAddress + (Reloc^ and
            $0FFF))^, ImageBaseDelta);
        Inc(Reloc);
      end;

      PReloc := pointer(Reloc);
    end;
  end;
  procedure ProcessImports(PImports: PImageImportDescriptor);
  var
    PImport:

    PImageImportDescriptor;
    Import: LPDword;
    PImportedName: pchar;
    ProcAddress: pointer;
    PLibName: pchar;
    ImportLoop:

    integer;
    function IsImportByOrdinal(ImportDescriptor: dword): boolean;
    begin
      Result := (ImportDescriptor and

        IMAGE_ORDINAL_FLAG32) <> 0;
    end;
  begin
    PImport := PImports;
    while PImport.Name <> 0 do
    begin
      PLibName :=

      pchar(cardinal(PImport.Name) + cardinal(ImageBase));
      if not Find(NewLibInfo.LibsUsed, PLibName, ImportLoop) then
      begin

        InjectLibrary(Process, PLibName);
        Add(NewLibInfo.LibsUsed, PLibName);
      end;
      if PImport.TimeDateStamp = 0 then
      begin

        Import := LPDword(pImport.FirstThunk + cardinal(ImageBase))
      end
      else
      begin
        Import :=

        LPDword(pImport.OriginalFirstThunk + cardinal(ImageBase));
      end;
      while Import^ <> 0 do
      begin
        if

        IsImportByOrdinal(Import^) then
        begin
          ProcAddress := RemoteGetProcAddress(Process, PLibName, pchar(Import^
            and $FFFF))

        end
        else
        begin
          PImportedName := pchar(Import^ + cardinal(ImageBase) +
            IMPORTED_NAME_OFFSET);
          ProcAddress :=

          RemoteGetProcAddress(Process, PLibName, PImportedName);
        end;
        PPointer(Import)^ := ProcAddress;
        Inc(Import);
      end;

      Inc(PImport);
    end;
  end;
begin
  ImageNtHeaders := pointer(int64(cardinal(Src)) +
    PImageDosHeader(Src)._lfanew);

  ImageBase := VirtualAlloc(Dest, ImageNtHeaders.OptionalHeader.SizeOfImage,
    MEM_RESERVE, PAGE_NOACCESS);
  ImageBaseDelta

  := cardinal(ImageBase) - ImageNtHeaders.OptionalHeader.ImageBase;
  SectionBase := VirtualAlloc(ImageBase,

    ImageNtHeaders.OptionalHeader.SizeOfHeaders, MEM_COMMIT, PAGE_READWRITE);
  Move(Src^, SectionBase^,

    ImageNtHeaders.OptionalHeader.SizeOfHeaders);
  VirtualProtect(SectionBase, ImageNtHeaders.OptionalHeader.SizeOfHeaders,

    PAGE_READONLY, OldProtect);
  PSections := pointer(pchar(@(ImageNtHeaders.OptionalHeader)) +

    ImageNtHeaders.FileHeader.SizeOfOptionalHeader);
  for SectionLoop := 0 to ImageNtHeaders.FileHeader.NumberOfSections -

  1 do
  begin
    VirtualSectionSize := PSections[SectionLoop].Misc.VirtualSize;
    RawSectionSize :=

    PSections[SectionLoop].SizeOfRawData;
    if VirtualSectionSize < RawSectionSize then
    begin
      VirtualSectionSize :=

      VirtualSectionSize xor RawSectionSize;
      RawSectionSize := VirtualSectionSize xor RawSectionSize;
      VirtualSectionSize :=

      VirtualSectionSize xor RawSectionSize;
    end;
    SectionBase := VirtualAlloc(PSections[SectionLoop].VirtualAddress +

      pchar(ImageBase), VirtualSectionSize, MEM_COMMIT, PAGE_READWRITE);
    FillChar(SectionBase^, VirtualSectionSize, 0);

    Move((pchar(src) + PSections[SectionLoop].PointerToRawData)^, SectionBase^,
      RawSectionSize);
  end;
  NewLibInfo.DllProc

  := TDllEntryProc(ImageNtHeaders.OptionalHeader.AddressOfEntryPoint +
    cardinal(ImageBase));
  NewLibInfo.DllProcAddress

  := pointer(ImageNtHeaders.OptionalHeader.AddressOfEntryPoint +
    cardinal(ImageBase));
  NewLibInfo.ImageBase :=

  ImageBase;
  NewLibInfo.ImageSize := ImageNtHeaders.OptionalHeader.SizeOfImage;
  SetLength(NewLibInfo.LibsUsed, 0);
  if

  ImageNtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress <> 0 then

    ProcessRelocs(pointer(ImageNtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress +

      cardinal(ImageBase)));
  if
    ImageNtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress <>

  0 then
    ProcessImports(pointer(ImageNtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress

      + cardinal(ImageBase)));
  for SectionLoop := 0 to ImageNtHeaders.FileHeader.NumberOfSections - 1 do
  begin

    VirtualProtect(PSections[SectionLoop].VirtualAddress + pchar(ImageBase),
      PSections[SectionLoop].Misc.VirtualSize,

      GetSectionProtection(PSections[SectionLoop].Characteristics), OldProtect);
  end;
  Result := NewLibInfo;
end

;

function

InjectLibraryEx(Process: LongWord; Src: Pointer): Boolean;
type
  TDllLoadInfo = record Module: Pointer;
    EntryPoint:

    Pointer;
  end;
var
  Lib: TLibInfo;
  DllLoadInfo: TDllLoadInfo;
  BytesWritten, TID: longword;
  ImageNtHeaders:

  PImageNtHeaders;
  pDllEntryPoint, pDllLoadInfo, pModule: Pointer;
  procedure DllEntryPoint(lpParameter: pointer);

    stdcall;
  var
    LoadInfo: TDllLoadInfo;
  begin
    LoadInfo := TDllLoadInfo(lpParameter^);
    asm xor eax, eax push eax push

    DLL_PROCESS_ATTACH push LoadInfo.Module call LoadInfo.EntryPoint
    end;
  end;
begin
  Result := False;
  if

  ((RT_GetVersion(nil) shr 31) = 1) then
    Exit;
  ImageNtHeaders := pointer(int64(cardinal(Src)) +

    PImageDosHeader(Src)._lfanew);
  pModule := xVirtualAllocEx(Process,
    pointer(ImageNtHeaders.OptionalHeader.ImageBase +

    $20000000), ImageNtHeaders.OptionalHeader.SizeOfImage, MEM_COMMIT or
      MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  if pModule

  = nil then
    Exit;
  Lib := MapLibrary(Process, pModule, Src);
  pDllLoadInfo := xVirtualAllocEx(Process, nil,

    SizeOf(DllLoadInfo), MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  pDllEntryPoint := xVirtualAllocEx(Process,

    nil, 1024, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  if pDllEntryPoint = nil then
    Exit;
  DllLoadInfo.Module

  := Lib.ImageBase;
  DllLoadInfo.EntryPoint := Lib.DllProcAddress;
  WriteProcessMemory(Process, pModule, Lib.ImageBase,

    Lib.ImageSize, BytesWritten);
  WriteProcessMemory(Process, pDllLoadInfo, @DllLoadInfo, SizeOf(DllLoadInfo),

    BytesWritten);
  WriteProcessMemory(Process, pDllEntryPoint, @DllEntryPoint, 1024,
    BytesWritten);
  if

  xCreateRemoteThread(Process, nil, 0, pDllEntryPoint, pDllLoadInfo, 0, @TID) <>
    0 then
    Result := True;
end

;

function

InjectExe(Process: LongWord; EntryPoint: Pointer): Boolean;
var
  Module, NewModule: Pointer;
  Size, BytesWritten, TID:

  longword;
begin
  Result := False;
  if ((RT_GetVersion(nil) shr 31) = 1) then
    Exit;
  Module :=

  Pointer(GetModuleHandle(nil));
  Size := PImageOptionalHeader(Pointer(integer(Module) +
    PImageDosHeader(Module)._lfanew

    + SizeOf(dword) + SizeOf(TImageFileHeader))).SizeOfImage;
  xVirtualFreeEx(Process, Module, 0, MEM_RELEASE);
  NewModule

  := xVirtualAllocEx(Process, Module, Size, MEM_COMMIT or MEM_RESERVE,
    PAGE_EXECUTE_READWRITE);

  WriteProcessMemory(Process, NewModule, Module, Size, BytesWritten);
  if xCreateRemoteThread(Process, nil, 0,

    EntryPoint, Module, 0, @TID) <> 0 then
    Result := True;
end;
end.

YOLO26算法婴幼儿面部情绪识别目标检测+训练好的模型+2681张数据集+pyqt可视化界面.zip 附训练好的 YOLO 权重与 PyQt 可视化检测界面,页面底部含可视化效果预览,毕设/课设开箱即用。 【数据集概况】 · 检测类别(中文):[哭泣(crying), 开心(happy)] · 总计:2681 张 · 测试集:186 张 · 验证集:0 张 · 训练集:2495 张 【训练曲线与评估图】 【模型训练配置】 参数 | 值 模型 | yolo26n 训练轮数 | 100 epochs 输入尺寸 | 640x640 批次大小 | 24 优化器 | auto 初始学习率 | 0.01 训练设备 【关键指标汇总】 训练了 100 个 epoch,最终轮指标: 指标 | 数值 mAP50 | **0.8069** mAP50-95 | 0.5664 Precision | 0.8700 Recall | 0.7726 train/box_loss | 0.7524 train/cls_loss | 0.4490 val/box_loss | 1.1351 val/cls_loss | 0.7588 【训练过程分析】 训练伊始,模型对 box_loss 和 cls_loss 的下降表现出惊人的效率,前 20 轮迅速将训练损失降至低位,显示了训练集的强大适应性。然而,在第 20 轮之后,loss 下降速度明显放缓,整体趋于平稳。到了 60 轮左右,box_loss 值逐渐接近 0.75,而 cls_loss 则稳定在 0.44 左右。从训练集的 box_loss 从 0.7524 降至 0.7325,能看出来 model 正在逐步优化每个实例的边界框准确性,这一过程在前 40 轮尤为显著。相比之下,cls_loss 从 0.4490 降至 0.4389,尽管变化不大,但整体上表现出了模型对类别的清晰度提升... 使用场景:毕业设计、课程设计、深度学习入门、工业场景落地验证。 立即下载

相关推荐

依赖专家资源的传统机构与依赖数据算法的现代平台,在转化效率上谁更胜一筹?.docx

依赖专家资源的传统机构与依赖数据算法的现代平台,在转化效率上谁更胜一筹?

DelphiXE2测试:从内存加载64位Dll

unit NtResDll; interface uses {$IFDEF DELPHI16}Winapi.Windows{$ELSE}Windows{$ENDIF}, {$IFDEF DELPHI16}System.SysUtils{$ELSE}SysUtils{$ENDIF}, {$IFDEF DELPHI16}System.Classes{$ELSE}Classes{$ENDIF}...

weixin_30530339的博客 632

PostgreSQL 数据库辅助类(要求 Npgsql 7.0 及以上) .NET Framework 4.7.2+ 或 .NET 6+;C# 7.3+

类别 :方法 数据源: Initialize、Close、DataSource、ConfigureBuilder、CommandTimeout、OnSqlExecuted 参数: CreateParameter(含类型版)、CreateJsonbParameter、CreateArrayParameter、ParamsFrom 执行: ExecuteNonQuery、ExecuteScalar<T>、ExecuteDataTable、ExecuteDataSet、ExecuteList<T>、ExecuteModel<T>、ExecuteDictionaryList、ExecuteColumn<T>、ExecuteReader(均有异步版) 封装: Exists、Count、ExecutePagedDataTable/List、Insert、Update、Delete、Upsert、TableExists、ColumnExists、GetTableNames、GetServerVersion、TestConnection 数据库对象: ExecuteFunctionTable/Scalar、CallProcedure 批量: ExecuteBatch(NpgsqlBatch)、BulkInsert(二进制 COPY)、CopyOut、ToDataTable 事务: ExecuteInTransaction(Async)、OpenTransaction(Async) 其他: Notify、ListenAsync、PgRetry(只读、显式调用)

动态链接库

参考:琢石成器   今天看《琢石成器》第11章,动态链接库和钩子,特此记录一下。   1、静态链接库 lib.exe工具将多个obj文件组合成一个lib文件,当程序需要用到这个lib文件中的子程序时,只需要指定子程序名,链接器就可以将代码插入到可执行程序中,这就是静态链接。 缺点: 1)、当多个程序要用到一段相同子程序时,就会存在相同代码,浪费空间(包括磁盘空间和多个程序装入内...

梦开始的地方 263

知识管理四款团队知识库选型对比:Confluence、OmniBox、语雀、Sward适用场景与部署方案分析

内容概要:本文对2026年主流的四款团队知识库工具Confluence、小黑OmniBox、语雀和Sward进行了横向评测,指出这四款产品并非直接竞争关系,而是分别对应不同组织状态下的解决方案。评测围绕部署方式、权限协作、检索与AI能力三大核心维度展开,强调选型不应仅看功能列表,而应关注资料来源、使用场景与团队特征。Confluence适合已有Atlassian体系的中大型企业,强在权限控制与流程治理;小黑OmniBox聚焦多源资料整合与AI问答,适用于资料分散的团队;语雀以“书本式”结构降低中文团队使用门槛;Sward则主打开源私有化部署,满足内网合规需求。文章最后提供四类典型团队的选型路径,并澄清了“AI万能”“私有化即安全”等常见误区。; 适合人群:企业IT负责人、技术管理者、知识管理相关从业者,尤其是面临知识库选型决策的团队领导者。; 使用场景及目标:①帮助团队根据自身规模、技术栈、数据主权要求和协作习惯选择合适知识库工具;②厘清AI与知识库的关系,避免选型误区;③指导已有系统如何与新工具(如OmniBox)叠加使用,提升知识利用率。; 阅读建议:此评测基于公开资料与产品文档,未进行压力测试或大规模实测,建议结合实际业务场景试用验证,并优先考虑现有系统兼容性与迁移成本。

基于深度学习分类的时相关MIMO信道的递归CSI量化(Matlab代码实现)

内容概要:本文系统阐述了基于深度学习分类的时相关MIMO信道递归CSI量化方法,并提供了完整的Matlab代码实现。该方法针对大规模MIMO系统中因信道状态信息(CSI)反馈开销过大而导致的系统效率下降问题,提出一种结合深度学习与递归结构的量化方案,利用分类网络对时域相关的CSI进行高效压缩,通过递归机制捕捉信道动态的时间连续性特征,显著提升了量化精度与频谱利用率。文中详细介绍了算法设计原理、神经网络架构选型、训练策略设计、损失函数构建及仿真验证流程,展示了在不同信道模型与时变条件下相较于传统量化方法的性能优势。; 适合人群:具备通信工程、信号处理或无线通信领域基础知识,熟悉MIMO系统原理与深度学习基本模型(如RNN、CNN)的研究生、科研人员及工程师,尤其适合从事智能通信、信道建模、CSI反馈优化等相关方向的研究者。; 使用场景及目标:①应用于大规模MIMO和5G/6G系统中的CSI反馈压缩与传输优化;②为时变无线信道环境下的高效信道量化提供基于深度学习的智能化解决方案;③支持科研复现实验,促进先进信号处理技术在通信系统中的融合与创新; 阅读建议:建议读者结合提供的Matlab代码逐模块调试运行,深入理解深度学习模型在信道量化任务中的输入输出设计、网络训练流程与性能评估方式,可尝试在不同信道参数(如多普勒频移、SNR)下进行仿真实验以验证算法鲁棒性与泛化能力。

进程注入方法之 CreateRemoteThread

<br />function TForm1.InjectDll(ThreadId: DWORD; DllFilename: string): Boolean;<br />var<br />  hProcess ,hThread :THandle;<br />  pszLibFileRemote:PChar;<br />  dwMemLen:DWORD;<br />  dwWrited:DWORD;<br />  pfnThreadRtn:Pointer;<br />  dwThreadId:DWORD;<b

zhaodog的专栏 821

konica C368(柯尼卡美能达bizhub C368系列打印机驱动)

1、查看本机 IP,确保电脑和复印机在同一个局域网。 2、安装时 右键以管理员运行 ,旧驱动先卸载干净避免冲突。 3、端口默认:9100(RAW),也可用 LPR。 安装方法: 1. 解压后进入文件夹,64 位运行 `Setup64.exe`,32 位运行 `Setup.exe`。 2. 同意协议 → 选择【安装(网络搜索)】,程序自动扫描局域网内 C368P。 3. 在列表选中对应 IP 的机器,下一步;如果扫不到,切换到【手动设置】,填入复印机 IP。 4. 勾选驱动类型(PCL6),点击安装,等待完成。 5. 安装结束,打印测试页验证。

MFC的消息响应函数

typedef struct  { UINT nMessage; UINT nCode; UINT nID; UINT nLastID; UINT nSig; int * p; }TEST; const TEST* AFXAPI MyAfxFindMessageEntry(const TEST* lpEntry, UINT nMsg, UINT nCode, UINT nID) { ASSERT(...

C++编程的专栏 3127

深度解读:车辆诊断之DTC的状态位

搞车辆诊断测试的,离不开对DTC的状态位的测试DTC的状态位是8个bit,每个bit代表不同的意思,每个bit置1或者置0都要满足一定的条件初学者,很容易被这个搞得头很大今天我们就来详细拆解一下,扫除你心中的疑惑我们以欠压故障为例进行说明,假设欠压故障(DTC code为EE0468)发生的条件如下:1. 车辆模式(CarModSts1)处于Normal(0)或者Dyno(5)2. 当电源可用性不受限制时,即ElPowerLevel (有和PwrLvlElecSubtyp组成。

帮助100万人颠覆负面潜意识,实现人生蜕变,培养1万名潜意识开发导师 1万+

IC设计新手必看:如何正确使用去耦电容(decap)避免电源噪声?

本文深入探讨了IC设计中去耦电容(decap)的应用技巧,从核心原理到布局实现,帮助新手工程师有效抑制电源噪声。文章详细解析了MIM、MOM等电容类型的特性与选择策略,并提供了先进的布局技巧和验证方法,特别适用于28nm以下先进工艺的电路设计挑战。

weixin_30555125的博客 119

模仿MFC寻找消息响应函数指针的 核心 代码

typedef struct  { UINT nMessage; UINT nCode; UINT nID; UINT nLastID; UINT nSig; int * p; }TEST; const TEST* AFXAPI MyAfxFindMessageEntry(const TEST* lpEntry, UINT nMsg, UINT nCode, UINT

C++编程的专栏 1064

【Python・统计学】(两)多因素方差分析(原理及代码)

自学笔记,分享给对统计学原理不太清楚但需要在论文中用到的小伙伴,欢迎大佬们补充或绕道。ps:本文不涉及公式讲解(文科生小白友好体质)~(部分定义等来源于知乎) 本文重点:多因素方差分析 【1.多因素方差分析简单原理】 【2.多因素方差分析步骤】 【3.多因素方差分析代码】

TUTO_TUTO的博客 4874

MFC EasySize - Dialog resizing in no time!

MFC EasySize https://www.codeproject.com/Articles/1657/EasySize-Dialog-resizing-in-no-time Usage Note that all this works exactly the same way with both CDialog and CPropertyPage Hide   Copy Code ...

jerryzfc的专栏 366

SEED-VII 实战指南:如何利用多模态脑电图数据提升情感识别精度

本文提供了SEED-VII多模态脑电图数据集的实战指南,详细介绍了如何利用该数据集提升情感识别精度。内容涵盖数据获取、预处理、特征提取,以及构建多模态融合神经网络模型的关键步骤,并强调了被试者独立评估的重要性,为情感计算研究者提供了从数据到模型的全流程解决方案。

weixin_29196891的博客 323

从基础知识到PCB设计,打造全能硬件工程师

成为一名出色的硬件工程师需要在多个领域建立坚实的基础。从硬件基础知识、元器件学习、模拟电子电路到PCB设计,以及数字电子电路与通信,每个方面都是构建全面硬件工程师技能集的重要组成部分。通过深入学习和实践这些领域,你将能够在硬件工程领域中取得更多的成就。

weixin_46969363的博客 2745

FWB information and questions

this is an addition to rob311&apos;s post with a few questions of mine, i&apos;m hoping some of you guys can help fill in the blanks.this from FWBSharp aphex&apos;s example:First there was FWB, DLL in

1566

2023年下半年网络工程师案例分析真题答案解析

R1] ip route-static 0.0.0.0 0.0.0.0 GigabitEthemet2/0/1 (3) track (4) R1 to R2 //配置R1的缺省路由,联动BFD使得R1到2的流量优先走R1->S1->R2链路,当此链路发生故障时,流量切换到R1->R3->R2链路上。当同一VLAN内也需要网络隔离时,我们可采用交换机的(2)功能,若在配置了二层隔离后,部分主机有互通的需求,则可在需求主机的网关上配置(3)功能。不需要,MAC地址是数据链路层封装以太帧的地址标识。

鹿鸣天涯 757

MFC under the hood

zzy5177的专栏 394

2026年大数据开发工程师常见面试选择题

大数据面试高频考点解析 摘要:本文汇总了30道大数据开发面试高频题目,涵盖Hadoop生态、Spark、Flink、Kafka等核心组件。重点包括:1)HDFS架构与特性(5V特征、副本机制);2)MapReduce/Spark原理(Shuffle过程、RDD抽象);3)实时计算(Kafka消费组、Flink Watermark);4)数据仓库设计(分层模型、性能优化)。特别强调数据倾斜、小文件问题等实战场景的解决方案,以及从日志、资源等多维度排查任务异常的方法。掌握这些基础原理和典型问题应对策略,是应对大

不务正业的猿 458

在 Fiori Elements Object Page 的表格中用 UI.Hidden 隐藏列:语义、边界与落地实践全解析

摘要: Fiori Elements的Object Page表格中,UI.Hidden注解支持静态和动态隐藏列。动态隐藏分为两种:基于父实体属性隐藏整列,或基于子实体属性按行隐藏单元格。关键约束包括:支持服务端操作的列禁止使用动态隐藏,否则会导致UX不一致。ABAP CDS不支持路径式UI.Hidden,需改用XML注解。该功能需与UI.Importance、个性化等机制明确区分,避免混淆。对于可能参与排序/过滤的列,建议仅使用静态隐藏。实际应用中需注意注解位置(整列或单元格级)和业务场景的匹配。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 208

OWASP MASVS贡献指南:从入门到参与移动应用安全标准建设

移动应用安全验证标准(MASVS)是移动应用安全领域的核心框架,为应用安全提供了系统化的验证基准。其原理在于通过分层(L1、L2、R)的安全要求,覆盖从基础防护到高级威胁抵御的完整生命周期,确保应用在开发、测试和部署各阶段的安全性。该标准的技术价值在于其开源性和社区驱动,能够持续集成最新的安全实践,例如应对AI大模型应用带来的新兴风险。在实际应用场景中,开发者、安全工程师和项目经理可依据MASVS进行安全需求分析、合规性审计和渗透测试。本文聚焦于如何有效参与OWASP MASVS项目,详细解析了包括文档改进

weixin_34037515的博客 370

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 通过 PEB 改变进程名,实现“穿透”防火墙
下一篇: inject的讨论
iiprogram
博客等级 码龄25年 1068粉丝 1515原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址